
Originally Posted by
bbomber72000
I got them and I'll post them later. But now I need an idea of how to use a for loop to check for prime numbers. I don't think I can use an if statement in a loop checking for predertimined values.
So does anyone have any ideas.
It should be obvious that you are to use what you were asked to do before, which is, to test if a number is an integer.
It's not actual c code, but you should be able to adapt it.
"number" = the number inputed.
Code:
bool isprime=true;
if ((number/2)-int(number/2) == 0.0)
{
isprime = false;
}
for (int i=3, i<=int(sqrt(number))+1 && isprime, i+2) /* We only need to test up to the square root for divisions,
since it's symmetrical. Also, if the number is a multiple of 2,
then we don't bother with the loop (isprime == false). */
{
if ((number/i)-int(number/i) == 0.0) /* Is the result of the division an integer? */
{
isprime = false; /* Result is an integer which means that i is a factor of number.
Also exits the loop */
}
}
if (isprime)
{
cout << "The number " << number << " is prime";
} else
{
cout << "The number " << number << " is not prime";
}
Edit: silly me, I forgot to comment. *adds comments to code*
Alternatively, you can test if "number mod i" == 0. If it's the case, it's not prime.
Edit2: Optimized the code to cut by two the number of iterations.