Hey guys, I was hoping someone could let me know if this is a good function to determine if the number in 'n' is a prime number. Here's why I have so far:
bool isPrime (long n)
{
long i = 0;
if(n == 1)
returnfalse;
elseif (n == 2)
returntrue;
elseif (n % 2 == 0)
returnfalse;
else
{
//check to see if it is prime
for (i = 3; i < n; i+=2)
{
if (n % i == 0)
returnfalse;
elseif (i == n)
returntrue;
}
}
return 0;
}
In the loop, we need to check for divisibility only up to (and including) the square root of n.
All prime numbers greater than 3 can be written as either 6*m - 1 or 6*m + 1 where m = 1, 2, 3, ....
So the trial divisions are required only if the remainder when divided by 6 is either 1 or 5.
you can reduce the time complexity of your algorithm. There are ways to do so, you can search the wikis.
In your code for instance iteration till n/2 shall serve the purpose instead of n.
also I would not include the following check:
else if (i == n)
return true;
the statement unnecessarily make checks at each iteration. I would simply return true whenever the program comes out of the "for" loop.