My goal is to display the first list of prime numbers depending on user's input, when the user input 10, the program should display first 10 prime numbers which are 2 3 5 7 11 13 17 19 23 29. I'm thinking of having generated list from 2 which is the first prime number to 541 which is the 100th prime number then if the user input for example 100 then it will be equivalent to 2 upto 541. Will my algorithm works? currently I'm able to display prime numbers from 2 - 541 and stucked on implementing another loop for 1-100 input.
#include <iostream>
using namespace std;
int main() {
int N, counter, i, j, isPrime, n;
cout << "List of prime numbers from 1-100: ";
cin >> N; // if the user input 10 then the first 10 prime numbers are "2 3 5 7 11 13 17 19 23 29"
// list of prime from 2-541 (or first list from 1-100 prime numbers)
for (i = 2; i <= 541; i ) {
isPrime = 0;
for (j = 2; j <= i/2; j ) {
if (i % j == 0) {
isPrime = 1;
break;
}
}
if (isPrime == 0 && N != 101)
cout << i << " ";
}
}
CodePudding user response:
Your current algorithm doesn't work, because N
is never modified. If the user inputs 101
then nothing will be printed, because if (isPrime == 0 && N != 101)
will always be false
. If the user inputs anything else then it will always print the first 100 primes.
The key idea will be to count how many primes were found and break after the N
th prime. Or count down, how many primes we still need t ofind. The rough outline will be as follows:
for (i = 2; N > 0; i ) { // Loop as long as we need to find more primes
...
if(isPrime == 0) {
std::cout << ...
N--; // <- Found one prime, N-1 to go
}
}