Preferred using bool isPrime(int number)
{
}
How to check a number isPrime using C++?
The largest possible factor of a number is number / 2 (if you think about this you should be able to verify it in your mind.)
int maxFactor = number / 2;
int testNumber = 2; //don't start at 1, everything is divisible by 1
if(number %26lt; 0)
{
throw logic_error;
}
while(testNumber %26lt;= maxFactor)
{
if(number % testNumber == 0) //if it divides evenly
{
return false;
}
else if(testNumber!=2)
{
testNumber+=2;
}
else if(testNumber == 2)
{
testnumber++;
}
return true;
}
Reply:You can do it quicker by only checking odd numbers after 3, and by stopping the search at the tested number's square root (rounded down to an integer).
Reply:Just like what lansingstudent09101 said but I am not exactly a C++ programmer although i did do it from age 8-11 (trust me i new how to do a lot) but make the int variables any thing you want but change the increment to NULL
funeral flowers
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment