Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exponential calculation in Python

While experimenting 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's the reason for this?

like image 731
Eugene Yarmash Avatar asked May 05 '15 22:05

Eugene Yarmash


1 Answers

The thing is python tries to print the first result. But this number has a zillion digits and python doesn't flush the output until a newline is encountered, which is after sending all the digits to standard output. As @abarnert mentioned, what is many times worse, is converting the number to string for printing it. This needs considerable memory allocation and processing power. On the other side, the second expression just needs to print a True. You can check it if you assign to the first expression:

 >>> a = 632382**518061

This way the output of the number is suppressed.

like image 51
JuniorCompressor Avatar answered Oct 14 '22 06:10

JuniorCompressor