Elliot Gorokhovsky
Elliot Gorokhovsky

Reputation: 3762

Python exponentiation order of operations and grouping

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

Upvotes: 3

Views: 307

Answers (1)

wim
wim

Reputation: 362806

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        

Upvotes: 10

Related Questions