Simple question:
Why does (7**3) ** 24 % 25
take almost no time to run, but 7 ** 3 ** 24 % 25
not terminate?
Asked
Active
Viewed 249 times
3

wim
- 338,267
- 99
- 616
- 750

Elliot Gorokhovsky
- 3,610
- 2
- 31
- 56
-
operator precedence .. – wim Apr 02 '15 at 03:42
-
@wim What specifically? If `%` takes precedence over `**` then it would compute 343 to the power of 24 which takes almost no time. Otherwise it's the same as the fast expression. – Elliot Gorokhovsky Apr 02 '15 at 03:43
1 Answers
10
Exponentiation groups from right to left.
So, 7 ** 3 ** 24
is evaluated as 7 ** 282429536481
(hard), whereas (7**3) ** 24
is just 343 ** 24
(easy).
As an interesting sidenote: CPython, which has a peephole optimiser, is able to optimise away the "easy" case with constant folding. But the "hard" case only gets as far as folding the 3 ** 24
.
>>> def foo():
return 7 ** 3 ** 24 % 25
...
>>> def bar():
return (7**3) ** 24 % 25
...
>>> dis.dis(foo)
2 0 LOAD_CONST 1 (7)
3 LOAD_CONST 5 (282429536481)
6 BINARY_POWER
7 LOAD_CONST 4 (25)
10 BINARY_MODULO
11 RETURN_VALUE
>>> dis.dis(bar)
2 0 LOAD_CONST 7 (1L)
3 RETURN_VALUE

wim
- 338,267
- 99
- 616
- 750
-
OOOOOOOOH yes! that's the same as in regular math. Sorry I'm stupid. – Elliot Gorokhovsky Apr 02 '15 at 03:47
-
2Yeah, 1.6910144928582986e+238680647722 is pretty big. :-) Of course if we only care mod 25, we can use the 3-argument form of pow to get the result quickly. – DSM Apr 02 '15 at 03:47
-
2When it's written with superscripts the order is obvious but in this notation I didn't realize what was going on. – Elliot Gorokhovsky Apr 02 '15 at 03:48
-
1