Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subtraction with large numbers

Tags:

python

I was playing around with large numbers in Python and I ran the calculation of

2**(1322134)  

and it obviously took a long time to calculate. However when I ran the calculation of

2**(1322134) - 2**(1322134)

it instantly returned 0.

How does Python automatically tell these are the same numbers without doing the calculations?

like image 440
Julian Avatar asked May 31 '26 05:05

Julian


1 Answers

The slow part is printing the number, not computing it:

In [1]: %timeit str(2**1322134)
1 loop, best of 3: 2.28 s per loop

In [2]: %timeit 2**1322134
10000000 loops, best of 3: 24.8 ns per loop

You can see this by storing the results in variables:

>>> x = 2**1322134
>>> y = 2**1322134
>>> x - y
0

The above code will execute instantly because Python won't have to print out almost 400,000 digits to your screen.

like image 192
Blender Avatar answered Jun 01 '26 19:06

Blender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!