var number;
Console.WriteLine("Accept number:");
number = Convert.ToInt32(Console.ReadLine());
if (IsPrime(number))
{
Console.WriteLine("It is prime");
}
else
{
Console.WriteLine("It is not prime");
}
public static bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
var boundary = (int)Math.Floor(Math.Sqrt(number));
for (int i = 3; i <= boundary; i += 2)
if (number % i == 0)
return false;
return true;
}
I changed number / 2
to Math.Sqrt(number)
because from in wikipedia, they said:
This routine consists of dividing n by each integer m that is greater
than 1 and less than or equal to the square root of n. If the result
of any of these divisions is an integer, then n is not a prime,
otherwise it is a prime. Indeed, if n = a*b is composite (with a and b ≠
- then one of the factors a or b is necessarily at most square root of n