1

is there a function or a simple class which let me check if a integer in c# is a prime or not?

gurehbgui
  • 14,236
  • 32
  • 106
  • 178

3 Answers3

4

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.

Kendall Frey
  • 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
3

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).

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

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;
}
aquinas
  • 23,318
  • 5
  • 58
  • 81
  • 1
    It 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