Initially, you might think that n/2 is the upper limit for which you must test to see whether a number is prime, but you need only go as high as the square root of n. Why?
Rewrite the program, and run it both ways. Estimate the performance improvement.
It's not wrong code, just very ineficient. You don't want to calculate the square root more than once, and you don't want to continue iterating when you find a case that fails the prime test.
1 2 3 4 5 6 7 8 9 10 11
int primeNumber(int x)
{
int prime = 0;
int squarert = sqrt(x);
for(int j = 2; j < squarert; j++)
{
if(x % j == 0)
return 0;
}
return x;
}
2 possibilities:
1) Add #include <cmath> at the top of your file
2) Change sqrt(x) to sqrt((double)x)
If you try to compile your code, it should give you an error which is more descriptive than a red line... That should help you to figure out what is wrong and/or which of the options above to use. If these steps don't work, give us that error message.
Initially, you might think that n/2 is the upper limit for which you must test to see whether a number is prime, but you need only go as high as the square root of n. Why?
Rewrite the program, and run it both ways. Estimate the performance improvement
This is what I have now , but the code is running nonstop when I debug it...