Printing first 20 prime numbers.

I know that there is a similar case posted here already but I just want to understand why my code doesn't work the way I wanted it to work.

#include <iostream>

using namespace std;

int main()
{
int num = 1;
int primeCount = 0;

cout << 1 <<endl;
for (int i = 0; i<20; i++){
num++;
primeCount = 0;

for (int j = 1; j<=num; j++){
if (num%j == 0){
primeCount++;
}
}
if (primeCount==2){
cout << num <<endl;
}

}
return 0;
}

The first for loop ensures that the process is repeated 20 times, right? However, when I run the program, it only prints the first 9 prime numbers which doesn't make sense to me. Please help.
closed account (SECMoG1T)
sorry to inform you but there are only 9 prime numbers between 1 and 20

1
2
for (int i = 0; i<20; i++){
num++; ///only goes upto 20 


reevaluate your logic
Last edited on
2, 3, 5, 7, 11, 13, 17, 19 ... that's EIGHT primes between 1 and 20.


https://en.wikipedia.org/wiki/Prime_number#Primality_of_one
Last edited on
I think that with the firs for loop you are checking for the first 20 numbers and there are 9 prime numbers to 20:1,2,3,5,7,9,11,13,17,19.If you would want to write a code for the first 20 prime numbers it is a little different.You need while if you want first 20 prime numbers but not prime numbers to twenty.

int main()
{
int num = 1;
int primeCount = 0;
int s = 1;
cout << 1 << endl;
while(s<20) //you already printed 1 so we need 19 more prime numbers
{
num++;
primeCount = 0;

for (int j = 1; j <= num; j++) {
if (num%j == 0) {
primeCount++;
}
}
if (primeCount == 2) {
cout << num << endl;
s++;
}

}
return 0;
}
Last edited on
Oh sorry my bad. Thank you very much for the help!
Topic archived. No new replies allowed.