I was attempting to solve Puzzle A14 found at http://chortle.ccsu.edu/CPuzzles/PartA/CpuzzlesAsection11.html, using Java (with Eclipse), when I came across some unexpected results.
The puzzle requires that on each line k, print all of the integers that are multiples of 23 in the range of 100 * k to 100 * k + 99 (where k is some limit, such as 11).
The Nested For Loop that I eventually used to solve the problem was:
for(i = 0; i <= k; i++){
for(j = 0; j <= 99; j++){
if((100 * i + j) % 23 == 0)
System.out.print(100 * i + j + " ");
}
System.out.println();
}
However, in my first attempt, I did not put parentheses around 100 * i + j before using modulo division in the If Statement and it produced only one line of results: "0 23 46 69 92" (as compared to the correct solution, which gave me 11 lines of results: "0 23 46 69 92" in the first line, "115 138 161 184" in the second line, etc.).
I was trying to figured out the reason behind this. Even without the parentheses, I would assume the If Statement was using modular division on j, before combining it with 100 * i. However, if that was the case, wouldn't it produce 11 lines (if k = 11) of "0 23 46 69 92" instead of just a single line?
This is due to operator precedence. The modulo (%
) operator as higher precedence over the plus and minus operators. See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html.
Take, for example, the case where i = 1
and j = 38
. In this case,
(100 * i + j) % 23
evaluates to zero and hence the condition is true. On the other hand, 100 * i + j % 23
evaluates to 115
and the condition is false.
The reason why only one line is printed when removing the parentheses is that when i > 0
(starting from the second line), the expression 100 * i + j % 23
will always be greater than 100, and therefore the condition of being equal to zero will always be false. Therefore, nothing will be printed starting at the second iteration of the outer for
loop.