Exponential Calculation in Python

During experiments with Euler 99, I noticed that these operations take different time:

>>> 632382**518061 # never finishes.. >>> 632382**518061 > 519432**525806 # finishes in few seconds True 

I wonder what is the reason for this?

+7
optimization python exponentiation largenumber
source share
1 answer

The thing is, python is trying to print the first result. But this number has a million digits, and python does not clear the output until a new line appears, which after sending all the digits to standard output. As @abarnert noted, it’s many times worse than converting a number to a string to print it. This requires a significant amount of memory and processing power. On the other hand, the second expression just needs to print True . You can check it if you assign the first expression:

  >>> a = 632382**518061 

Thus, the output of the number is suppressed.

+12
source share

All Articles