View Single Post
Old Aug 30th, 2006, 9:25 PM   #5
Kaja Fumei
Hobbyist Programmer
 
Join Date: Oct 2005
Posts: 134
Rep Power: 3 Kaja Fumei is on a distinguished road
Couple of comments on Jimbo's isPrime():
1. It assumes the input is an odd number. While it always true in this context when prime() calls it, a seperate call to isPrime(14) will return true instead of false because it is not checked for being a multiple of 2, and the loop will break before it reaches the other factor of 7.
2. In the n < 9 case, I think you meant to use "&&" instead of "||". And there needs to be a special case for when n is 2, because 2 is both even and prime.

While the isPrime() works perfectly when called by the current prime() function because the input is never even or less than 9, it would yield incorrect results if called by another function that didn't filter anything out first.

Here's an isPrime() that should work from any context:
cpp Syntax (Toggle Plain Text)
  1. bool isPrime(unsigned int n)
  2. {
  3. if(n < 9) // cover any n < 9; assumes 1 is prime
  4. return n % 2 == 1 || n == 2; // true if odd or 2
  5. else if(n % 2 == 0) // quick check for evens
  6. return false;
  7.  
  8. for(int i = 3; i*i <= n; i+=2)
  9. {
  10. if(!(n%i))
  11. return false;
  12. }
  13. return true;
  14. }
Kaja Fumei is offline   Reply With Quote