C++ Prime Numbers

How this code actually works

1
2
3
4
5
6
7
int i, j;

	for(i=2; i<16; i++) {
		for(j=2; j<=(i/j); j++) //confused
			if(!(i%j)) break ;
		if(j>(i/j)) cout<<i<<" / "<<j<<endl; //even more
                  }
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
#include <iostream>
using namespace std;

int main() {
    int i, j; // Declare two new integer variables, named 'i' and 'j',

    for (i = 2; i < 16; i++) {
        /* "int i = 2;" - Initalize 'i' with a value of 2.
               This is the index integer.
           "i < 16;" - While the value of 'i' is less than 16. The loop will
                continue until this expression becomes true, so it will iterate
                14 times in this case.
           "i++" - Increment the value of 'i' by 1. '++' is the Increment operator.
                It is equivalent to "i += 1;" or "i = i + 1;"
          So, it basically means: 'i' is 2; keep going as long as 'i'
              is less than 16, stop when it is 16; increment 'i' by 1;
              Perform below actions while condition is true.
          To sum it up even more, it means "Do each of these things below
              while i < 16 and increment i by one each time until it hits 16" */

        for (int j = 2; j <= (i / j); j++)
            /* Initialize 'j' with a value of 2;
                   while j is less than or equal to  i divided by j; increment j;
                   Do these things while condition is true: {things;} */
            if (!(i % j)) break; /* Try to divide i by j, if not successful then
                                    break the for loop;
                                        ! is the 'NOT TRUE' operator.*/
        if (j > (i / j)) // If j is greater than i divided by j,
            cout << i << " / " << j << endl; // print the value of i, then a slash,
                                             //   then the value of j,
                                             //   followed by a newline;
    }
}


For more info on for loops, see http://www.cplusplus.com/doc/tutorial/control/

PS: Don't try to compile the code I posted above, I think I messed something up while typing the comments, so it doesn't function right.
Last edited on
1
2
3
            if (!(i % j)) break; /* Try to divide i by j, if not successful then
                                    break the for loop;
                                        ! is the 'NOT TRUE' operator.*/

What...?

You divide i by j, if there is no remainder, it breaks the loop.

Also this thread has been posted elsewhere.
Last edited on
Yeah, I thought something like that, I don't really understand the modulo operator that well...
Example;
25%12 returns the remainder of 25/12, wich is 1

So with i%j, if i%j would return 0, you can divide i by j without having a remainder, if thats the case, i isnt a prime number
Last edited on
Topic archived. No new replies allowed.