printing the first n prime numbers (user input)

Jan 15, 2014 at 1:36pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

//Finding prime numbers
#include <iostream>
using namespace std;

int main()
{
int n; //User input
int num = 1; //number that will be tested if its a prime
int primeCount = 0; //counts the times it num % i == 0

cout<< "Enter how many prime numbers you want. ";
cin>> n; //Number of prime numbers you want

//prints 1 as a prime number
cout<< 1 << '\n';

//counts the number of primes
for(int j = 1; j <= n; j++)
{
    num++;//num = 2
    primeCount = 0;
//Determines if a number is prime
    for(int i = 1; i <= num; i++)
    {

        if(num % i == 0)
        {
            primeCount++;
        }
    }
        if(primeCount == 2)
        {
            cout<< num << '\n';
        }
}
return 0;
}



/*The program currently prints all the prime numbers up to n (For example, if 7 is entered, it prints out: 1, 2, 3, 5, 7.  What I want it to do, is print out the first 7 numbers; 1, 2, 3, 5, 7, 11, 13.  
I cannot figure it out.  Please help.
*/

Jan 15, 2014 at 1:39pm
Instead of looping n times you can loop as long as primeCount is less than n.
Topic archived. No new replies allowed.