The problem lies with this section:
// Print prime numbers
if (status != 0){
cout << num << endl;
count++;
// If printed number is greater than n, stop the loop and printing
if (num >= n){
status = 0;
break;
}
}
Since you check if num
exceeds your end n
only after you print the number, you'll end up printing one extra prime number. To fix this, you could simply rearrange your code a little, to only print after checking the condition:
// Print prime numbers
if (status != 0){
// If number is greater than n, stop the loop and printing
if (num > n){
status = 0;
break;
}
cout << num << endl;
count++;
}
Note how I also changed the num >= n
to just num > n
. This will ensure that if n
is a prime number, it will still be printed. (So the maximum of the range you specify will be inclusive.) Hope this helped! Let me know if you have any questions.