Tom
Tom

Reputation: 23

Prime number calculator C++

I've been trying to write a program to print out the prime numbers up to a value N.

When running the program, I am prompted to input a value of N as expected, but when I press return, the program ends. I think the problem may lie in the break statement:

if (modulo == 0) break;

Despite reading that 'break' will end only the nested loop and not both, I see it as the only thing that might be going wrong. When I replace this with 'continue', the program prints out all integers from N to 0, so if I input N=20, the output is 20, 19, 18, ... 3, 2,

The relevant section of the code follows, any help/advice for a total C++ novice would be greatly appreciated.

int N, f;
float modulo;

cout << "Welcome to the prime number sieve\n";
cout << "Enter the number up to which the prime numbers will be printed: ";
cin >> N;

for (int j = N; j != 1; j--) {              
    f = j;

    for (f; f != 0; f--) {
       modulo = j%f;
        if (f == 1) {
            cout << j << ", ";
        }   
        if (modulo == 0) break;
        }                                         

}

  return 0;

Upvotes: 0

Views: 2717

Answers (1)

nem035
nem035

Reputation: 35481

You algorithm is wrong. No matter what the number is, the break in the second loop will happen right away.

let's say input is 20. Then

first iteration:

j = 20
f = j = 20
modulo = 20 % 20 = 0
break

second iteration:

j = 19
f = j = 19
modulo = 19 % 19 = 0
break

And so on... first thing you should do is look up Sieve of Eratosthenes

And for your program, how bout this (Explanation):

for (int j=2; j < N; j++) {
    for (int f = 2; f*f <= j; f++) {
        if (j % f == 0) {
            break;
        }
        else if (f+1 > sqrt(j)) {
            cout << j << " ";
        }
    }   
}

Upvotes: 1

Related Questions