what I do not understand and still do not grasp is how did the two loops give birth to prime numbers?????? |
In simple terms - as I suggested earlier - thinking of the code as "a block of code which does something", it is the inner loop which does the important work. The outer loop is simply feeding numbers, one at a time to the inner loop. What the inner loop does is to test the number, to determine whether or not it is prime.
In order to fully understand what it does, you need to understand not simply how c++ works, but you need to understand how a prime number is defined, and how it behaves.
Let's say we take the number 7, we want to know whether it is prime. So we divide by each integer starting with 2 and less than 7, and see whether there is any remainder:
7 % 2 = 1
7 % 3 = 1
7 % 4 = 3
7 % 5 = 2
7 % 6 = 1 |
As you can see, there is some remainder every time.
Now try again with the number 15:
15 % 2 = 1
15 % 3 = 0
15 % 4 = 3
15 % 5 = 0
15 % 6 = 3
15 % 7 = 1
15 % 8 = 7
15 % 9 = 6
15 % 10 = 5
15 % 11 = 4
15 % 12 = 3
15 % 13 = 2
15 % 14 = 1 |
Notice that this time the remainder is zero on two occasions.
For the purposes of testing whether a number is prime, it only has to give a zero remainder once for it to be non-prime, so the testing could have been interrupted after testing 15%3. The remaining tests don't cause harm, but they are a waste of time.
Now if you go back and look at the code above, you will see a variable
bool prime
which is used in order to keep track of the outcome. It is set to
true
at the start. If it is still
true
at the end, the number is prime. If it is
false
it means there was a remainder of zero at least once, indicating the number has at least one factor, and is therefore not prime.