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.
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++;
}