Checking for a prime number

Checking for a prime number

Rate This
  • Comments 3

Ok, looking back at the original post I'm nearly regretting it as I need to find the time to actually write these - but at least this one was quick and simple. In fact it may be too simple to use as a tech test, but anyways here it is.

A prime number is any number greater than 1 which is only divisible by itself and 1. The method I use here simply checks all the values up to the number under investigation to see if division by them would leave a remainder of zero. There are probably faster ways to do this using smarter maths, and if you know of one, please post a comment!

 

 private static bool IsPrime(int num)
{
if (num <= 1)
{
return false;
}

for (int i = 2; i < num; i++)
{
if (num % i == 0)
{
return false;
}
}

return true;
}
Blog - Comment List MSDN TechNet
  • Loading...
Leave a Comment
  • Please add 5 and 6 and type the answer here:
  • Post