简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM