help with prime numbers program

#include "stdafx.h"
#include "iostream"
using namespace std;
int main ()
{
int x;
int i;
int e;

cout <<" choose a number to check if prime ";
cin >> x;
for ( i=1 ;i<=x; i++ )
if ( x%i==0)
{
cout <<" prime number" ;
}
else
{
cout <<" not prime number" ;
}
cin >> e;
return 0;
}
is the logic good ? and why the program is looping
The logic is incorrect. First, you start from one; every number is divisible by one. Your loop should start from the number 2, which is the first prime number. Secondly, x%i == 0 indicates that x is evenly divisible by an integer, meaning that it is not prime.
Your program does a cout for each value of i, rather than waiting to determine if any or all values of i are x % i = 0.

Run all relevant values of i first, then report one time if x is prime or not. You only need to run the loop until i reaches the square root of x.

I started out with assuming the number was prime by a flag <isprime= true>, then used this:

1
2
3
4
5
6
for ( i = 2; i * i < x && isprime ; i++ ) // isprime is a bool value initialized to true
{
     isprime = ( x % i > 0);
}

//now do your cout based on logical value of isprime 


Last edited on
One error I thought of last night while going to sleep:

this loop will report that 9, 49, 121, 169 etc (squares of primes) are prime, which they are not. Needs to check for i * i <= x.

One small character. . .
Topic archived. No new replies allowed.