I am tasked with creating a program that outputs the first N prime numbers. The user inputs the value N. Here is my current program. It may look weirdly formatted but I don't know how to fix that. It's pretty easy to see what is happening though.
#include <iostream>
using namespace std;
int main() {
cout << "How many prime numbers?";
int N;
cin >> N;
if(N=1){
cout << "2";
}
if(N>1){
cout << "2" << "\n";
int i=N-1; //i=prime counters
int j=3; //j=test prime
do {
int k;
for(k=2; k<j;){ //divisibility test
if(j%k!=0 and k!=j-1){ //indivisible, check next divisor
k=k+1;
continue;
}
if(j%k!=0 and k==j-1){ //indivisible and last divisor, display prime
cout << j << "\n";
i=i-1 //removes a prime counter
break;
}
if(j%k==0){ // divisible, break from loop
break;
}
}
j=j+1; //test next prime
} while(i>0); //will not continue printing primes if number has exceeded N
}
return 0;
}
The program outputs "2" no matter what. Then, it tests each number for divisibility with every number before it except for 1. If it is indivisible and still has divisors to get through, it continues. If it is indivisible and has no more divisors left, it is printed, and one "prime counter" is taken away. If it is divisible, the loop is broken and it moves on to test the next number. When the prime counters reach 0, the do while loop ends and the program is complete.
I reached an issue with the program when it outputted the following:
How many prime numbers? 2
I have no idea why this is happening since I specified N as an integer and asked for the user to input N. It doesn't even give me the opportunity to input N, it just automatically prints "2". What is going on?