Let’s first start with the most basic one (or by the book definition J). Here we will traverse from 2 to less than a given number and check if the number is divisible by any of them, if yes then it’s not prime.
public static bool CheckPrimeNumber1(int num)
{
if (num == 1)
return false;
for (int i = 2; i<num; i++)
{
if ((num % i) == 0)
{
return false;
}
}
return true;
}
Now let’s see a better one, it’s almost similar to the above, however the traversing is being done only till half.
public static bool CheckPrimeNumber2(int num)
{
if (num == 1)
return false;
for (int i = 2; i <= num/2; i++)
{
if ((num % i) == 0)
{
return false;
}
}
return true;
}
Now we will increase the efficiency, let’s park the numbers from a loop which are even and more than 2 (as they are obviously not prime, rightJ) and also start a loop from 3 and jumps by two numbers (as the even numbers have already been filtered).
public static bool CheckPrimeNumber3(int num)
{
if (num == 1)
return false;
if (num > 2 && (num % 2) == 0)
{
return false;
}
for (int i = 3; i <= num / 2; i+=2)
{
if ((num % i) == 0)
{
return false;
}
}
return true;
}
return true;
Now what? You are right J the most efficient one... In addition to the above, it’s only checking with the squares. It’s really bringing down the iterations to the lowest, right! Check it out.
public static bool CheckPrimeNumber4(int num)
{
if (num == 1)
return false;
if (num > 2 && (num % 2) == 0)
{
return false;
}
for (int i = 3; i*i <= num; i+=2)
{
if ((num % i) == 0)
{
return false;
}
}
return true;
}
One more thing please, do let me know about your comments/suggestion or if you have any better way to do this.
No comments :
Post a Comment