I would just like to ask if this is a correct way of checking if number is prime or not? because I read that 0 and 1 are NOT a prime number.
int num1;
Console.WriteLine("Accept number:");
num1 = Convert.ToInt32(Console.ReadLine());
if (num1 == 0 || num1 == 1)
{
Console.WriteLine(num1 + " is not prime number");
Console.ReadLine();
}
else
{
for (int a = 2; a <= num1 / 2; a++)
{
if (num1 % a == 0)
{
Console.WriteLine(num1 + " is not prime number");
return;
}
}
Console.WriteLine(num1 + " is a prime number");
Console.ReadLine();
}
To prove whether a number is a prime number, first try dividing it by 2, and see if you get a whole number. If you do, it can't be a prime number. If you don't get a whole number, next try dividing it by prime numbers: 3, 5, 7, 11 (9 is divisible by 3) and so on, always dividing by a prime number (see table below).
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
Using Soner's routine, but with a slight variation: we will run until i
equals Math.Ceiling(Math.Sqrt(number))
that is the trick for the naive solution:
boolean isPrime(int number)
{
if (number == 1) return false;
if (number == 2) return true;
var limit = Math.Ceiling(Math.Sqrt(number)); //hoisting the loop limit
for (int i = 2; i <= limit; ++i)
if (number % i == 0)
return false;
return true;
}
Here's a nice way of doing that.
static bool IsPrime(int n)
{
if (n > 1)
{
return Enumerable.Range(1, n).Where(x => n%x == 0)
.SequenceEqual(new[] {1, n});
}
return false;
}
And a quick way of writing your program will be:
for (;;)
{
Console.Write("Accept number: ");
int n = int.Parse(Console.ReadLine());
if (IsPrime(n))
{
Console.WriteLine("{0} is a prime number",n);
}
else
{
Console.WriteLine("{0} is not a prime number",n);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With