Here's my C++ code:
bool isPrime(double value) {
if (value == 2) // ensure 2 returns true
return true;
else if (value <= 1) // eliminate 1 and all negative numbers
return false;
else if (fmod(value, 2) == 0) // eliminate all even numbers
return false;
for (int i = 3; i < sqrt(value); i++) {
if (fmod(value, i) == 0) {
return false;
}
}
return true;
}
This function should return true if a number given by value is a prime, and false if a number given by value is a composite. First off, I just want to make sure it works correctly, is fairly efficient (it doesn't have to be the best, but I would like it to be decent for a naive approach), and that the code looks nice.
Thanks!
fmod()
on your system, but statements likeif ((value & 0x1) == 0)
is likely a faster way to detect even numbers. That's possibly the case withfmod()
in your for loop as well. You could useif ((value % i) == 0)
instead. \$\endgroup\$ – Jonathan Wood Feb 6 '12 at 17:55