is there a function or a simple class which let me check if a integer in c# is a prime or not?
-
This should get you started: http://en.wikipedia.org/wiki/Primality_test – Jamiec Aug 24 '12 at 15:37
-
Why would there be ? It's not a common task and the exact way to compute it (with all intermediate data) really depends on the sequence of number on which you'll need this information. – Denys Séguret Aug 24 '12 at 15:37
-
possible duplicate of [Program to find prime numbers](http://stackoverflow.com/questions/1510124/program-to-find-prime-numbers) – derekerdmann Aug 24 '12 at 15:38
-
i thought there is one because the size of a int32 is very restricted – gurehbgui Aug 24 '12 at 15:43
-
Sounds like homework help to me... – PhonicUK Aug 24 '12 at 15:48
3 Answers
No.
You'll need to write your own.
The basic algorithm for one single integer is to divide it by all integers up until it's square root and ensure that there is always a remainder.
To check more than one number, optimized algorithms such as the Sieve of Eratosthenes are available.

- 43,130
- 20
- 110
- 148
-
Isnt the SoE used to find all of the primes up to some integer? The OP seems to want a simple primality test: http://en.wikipedia.org/wiki/Primality_test – Chris Shain Aug 24 '12 at 15:39
There is no reason to have a standard prime checking function.
This is an expensive computation which can be made in different ways, each one having different impacts on memory and cpu.
And it really depends on the size of the numbers and the sequence of number whose primality you'll have to test, as there are usually intermediate values to store.
Said otherwise : the solution you'll chose will have to be adapted to your program and your exact need. I suggest you start by looking at wikipedia (credit to Chris Shain for the link) and by existing libraries like this one for small integers (credits to Google for the link).

- 372,613
- 87
- 782
- 758
-
-
@gurehbgui OP mentioned integer, not int... `2^(3339383383838382924334487888373881717878333)-1` is an integer. – Denys Séguret Aug 24 '12 at 15:44
Here's the one I use for all my project euler problems.
private static bool IsPrime(long number) {
if (number <= 1) return false;
for (long i = 2; i <= Math.Sqrt(number); i++) {
if (number % i == 0)
return false;
}
return true;
}

- 23,318
- 5
- 58
- 81
-
1It can be more efficient if you check number % 2 == 0 first. Then you start the for(...) loop with i = 3 and increment by 2 (i += 2). – Inisheer Aug 24 '12 at 15:45