0

Possible Duplicate:
C++ Prime Numbers program

I am working on a c++ program to calculate all prime numbers between 3 and an integer 'x'. When I enter 10 as 'x' I am getting the output: 3 5 5 5 7 7 7 7 7 9

Can anyone tell me how to fix this?

#include <iostream>
#include <cmath>

using std::cout;
using std::endl;
using std::cin;

int main(){

   int x;
   int i;
   int j;

   cout << "Please enter an integer 'x' greater than 3: " << endl;

   cin >> x;

   if (x <= 3){

        cout << "Please enter new value 'x' greater than 3: " << endl;

        cin >> x;
   }
        for(int i=3; i<=x; i++){
                for(j=2; j<i; j++){
                   if(i%j == 0)
                        break;
                   else if(i == j+1);
                        cout << i << endl;
                   }
        }
        return 0;
}
Community
  • 1
  • 1
Jessica
  • 45
  • 1
  • 3

2 Answers2

4

Offending line:

else if(i == j+1);

Remove the semi-colon.

paddy
  • 60,864
  • 6
  • 61
  • 103
  • This made it work perfectly, thank you very much! :) – Jessica Jan 29 '13 at 04:08
  • No worries. For an extra challenge, you should try implementing the Sieve of Eratosthenes as suggested by Arun Saha. I did a little experiment with it a couple of days ago, and found it took less than 200 milliseconds to calculate primes up to 15 million. – paddy Jan 29 '13 at 04:24
1

You may want to check out the Sieve of Eratosthenes.

Arun
  • 19,750
  • 10
  • 51
  • 60