Prime Numbers

Hi

I have this code that works for finding a user defined amount of prime numbers.
I however do not completely understand it and was wandering if someone could explain it. Also, how could you write this loop for (int i=2, k=0; k<n; i++) as two seperate loops?

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
  #include <iostream>

using namespace std;

int main()
{
    int num;
    cout << "Enter a number ";
    cin >> num;
    cout << "The first " << num << " prime numbers are: ";

    for (int i=2, k=0; k<n; i++){
        for (int j=2; j<i; j++){
            if (i%j == 0)
                break;

            else if (i == j+1){
                cout << i << " ";
                k++;
            }
        }
    }

return 0;
}


Regards
Jason McG
The code above finds the first num prime numbers by applying the rule the defines a prime number to each number from 2 - inf.

Rule:
wikipedia wrote:
[A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself...]http://en.wikipedia.org/wiki/Prime_number

Once you understand the rule, it should be obvious what the code is doing. Note that this method of finding primes is the bruteforce method, there are other more effiecient and faster methods. http://www.troubleshooters.com/codecorn/primenumbers/primenumbers.htm

You can't write that for-loop as 2 separate loops in the way it is used in code. You can however make it shorter by doing:

12
13
14
15
16
17
for (int i = 2; num > 0; i++)
    ...
    else if (i == j+1) {
        cout << i << " ";
        num--;
    }
Last edited on
The problem with changing the for loop for (int i = 2; num--; i++) is that it prints out the prime numbers untill 'num', and not 'num' amount of prime numbers.
Ok I just corrected it
Cool thanks!
Topic archived. No new replies allowed.