Reputation: 37
I need the output to read the number then whether the number is prime or not. For some reason when it gets to 11 it wont output that it is prime and just prints 11 12 That number is not prime.
I know theres a logical problem with my while loop but I cant figure it out. Any help is appreciated.
int main()
{
bool isPrime = true;
int sqrtNum;
int divisor = 3;
for(int i = 0; i < 100; i++)
{
cout << i << "\t";
if (i == 0 || i == 1)
cout << "That number is not prime." << endl;
else if (i == 2)
cout << "That number is prime." << endl;
else if (i % 2 == 0)
cout << "That number is not prime." << endl;
else
{
sqrtNum = static_cast<int> (sqrt(static_cast<double>(i)));
while (divisor <= sqrtNum)
{
if (i % divisor == 0)
{
cout << "That number is not prime." << endl;
isPrime = false;
break;
}
else
{
divisor = divisor + 2;
}
}
if (isPrime)
{
cout << "That number is prime" << endl;
}
}
}
system("pause");
retu
Upvotes: 0
Views: 66
Reputation: 206747
As is clear from the comments, you forgot to reset the values of isPrime
and divisor
in the loop. In order to avoid errors like this, it is best to define such variables only in the scope where they are used.
int main()
{
for(int i = 0; i < 100; i++)
{
cout << i << "\t";
if (i == 0 || i == 1)
cout << "That number is not prime." << endl;
else if (i == 2)
cout << "That number is prime." << endl;
else if (i % 2 == 0)
cout << "That number is not prime." << endl;
else
{
bool isPrime = true;
int divisor = 3;
int sqrtNum = static_cast<int> (sqrt(static_cast<double>(i)));
Upvotes: 3