Einfach Test für Primzahlen.
public bool IsPrime(int number)
{
if (number == 1)
return false;
else if (number < 4)
return true; // 2 and 3 are prime
else if (number % 2 == 0 || number % 3 == 0) //filter all even numbers, as all primes except 2 are odd
return false;
else if (number < 9) //4,6,8 have been excluded already
return true;
else
{
int r = (int)Math.Sqrt(number); //flooring the sqrt of number
int s = 5;
while (s <= r) //to find a number f less than or equal to the sqrt of n, that divides n
{
if (number % s == 0)
return false;
else if (number % (s + 2) == 0)
return false;
s += 6;
}
}
return true; //in all other cases
}
1 Kommentare zum Snippet