The x += x
doubles x
every time the innermost statement is executed.
The inner loop is executed 1 + 2 + 3 + 4 = 4 * (4 + 1) / 2 = 10
times. Thus, the result must be 2^10 = 1024
.
For general n
, it should be something like 2^((n + 1) * n / 2)
.
The fact that 1 + 2 + ... + n = (n + 1) * n / 2
is sometimes called “Gaussian sum formula”, you should remember it next time you see two nested loops where the range of the inner index depends on the outer index.
6
solved Calculating without running the program [closed]