If we go back to this line:
for (i = 2; i < (num / 2) + 1; i = i + 1)
what is it saying?
It says variable
i
starts from 2. It is increased by 1 at the end of each iteration.
for (i = 2; ........; i = i + 1)
What does the part in the middle do? It is a
condition
. The condition is tested, if it is true, the body of the loop is executed.
Let's say that
num
is 100.
(num/2)
will be 50. If the condition is
i < (num / 2)
that is saying, the same as
i < 50
The result would be the loop is executed for all values of
i
from 2 to 49 inclusive.
If we add 1, the condition becomes
i < 51
, now the loop is executed for values from 2 to 50. It includes 50, rather than stopping at 49.
Personally I'd have used a <= operator instead,
i <= (num / 2)
Also 100 is 100's divisor too but on this way the program will never find it out. |
That is true. But the same applies to 1, which is also ignored. Partly it comes down to interpretation of the question. But either way, going through twice as many calculations just to arrive at something which is already a certainty would be a poor design. We know already that none of the values 51 to 99 will be factors. We also know that 100 will be a factor. There's no need to do multiple iterations to determine something which we already knew in the first place.