Prime Number Counter

I need this to print out the amount of prime numbers that the user inputs, however my code stops to soon. Spent too long trying to find my errors and am throwing a last hope plea for help to you all. Any help would be much appreciated!

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
  //Finding prime numbers
#include <iostream>
using namespace std;

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

cout << "Enter how many prime numbers do you want? ";
cin >> n;
cout << "The first " << n << " prime numbers are:" << endl;


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;
}
Two problems:
1) Your loop at 19 is counting both prime and non-prime numbers.
2) Your algorithm is wrong inefficient. You're counting how many numbers divide evenly into num. If ANY number divides evenly into num, then num is NOT prime.

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    bool is_prime;
    int j = 0;
    //counts the number of primes
    do 
    {   is_prime = true;    //  Assume it's prime
        num++; 
        //Determines if a number is prime
        for (int i = 2; i < num; i++)
        {   if (num % i == 0)
            {   is_prime = false; 
                break;  // No point in checking further
            }
        }
        if (is_prime)
        {   cout << num << '\n';
            j++;  // Count the number of primes
        }
    }
    while (j < n);
Enter how many prime numbers do you want? 10
The first 10 prime numbers are:
1
2
3
5
7
11
13
17
19
23
29

Edit: On second thought your algorithm is probably fine, although inefficient, checking that there are exactly two numbers that divide evenly into num. The better approach is to stop checking when the first evenly divisible divisor is found.
Last edited on
Topic archived. No new replies allowed.