1

Can anyone help me out? I am trying to test primality but I cant seem to get this to work. For whatever reason, whenever I run it, it runs fine as long as I start with a number that is not prime. However, after running something that is not prime, the output is "0 1" instead of just 0. It also seems that if I start with a number that is not prime, everything is "0 1" instead of the correct output.

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <cmath>

int main()
{
    int num;
    int x = 2;
    //cin >> num;
    while(cin >> num)         //(x<=num-1) 
    { 

        for(x<=num-1; x++;)
        {
            if(num%x==0)
            { 
                cout << "0" << endl ; //1 is prime, 0 is not prime
                break; 
            }

            if(x==num)
            {
                cout << "1" << endl ;
                break; 
            }
        }

        if(x==num)
        {
            cout << "1" << endl ;
        }

    }

    return 0;
}

2 Answers2

1

well you have the cout << "1" twice, you probably didn't mean that

pm100
  • 48,078
  • 23
  • 82
  • 145
0
for(x<=num-1; x++;)

the semicolons are in wrong places, so instead of stating a condition x<=num-1 under which execution should happen you state the x<=num-1 expression is just evaluated with no effect and then in case of a prime number x is incremented until

if(num%x==0)

is true because in fact num==x at this point. Then you print your '0' and next you print '1' because

if(x==num)
{
  cout << "1" << endl ;
}

is true.

4pie0
  • 29,204
  • 9
  • 82
  • 118