Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can python naturally support big integer and be efficient?

In python, if we let a=2*4, then "a" will be of integer type. But if we let a = 2**400, then "a" will be automatically be of long type, which is java's BigInteger counterpart.

Thus Python can automatically convert an integer to a BigInteger when it is necessary. My question is: If every time it performs an arithmetic operation on an integer, Python checks whether this operation causes overflow or not. If overflows, convert it to BigInteger. Wouldn't it be very costly? Because this basically means Python inserts an overflow-checking instruction after every integer arithmetic instruction. So how can python naturally support big integer and be efficient?

like image 355
Zero Liu Avatar asked Feb 08 '23 12:02

Zero Liu


1 Answers

Wouldn't it be very costly?

Absolutely, but this is far from the most costly thing involved. We also have dynamic dispatch on the arithmetic operations involved and dynamic allocation of objects to hold the result, among other things.

So how can python naturally support big integer and be efficient?

If your algorithm spends all its time doing Python-level arithmetic with Python integers, it won't be efficient. It'll be slow as hell. In that case, you probably want to use something like NumPy or C instead of Python integer arithmetic.

like image 67
user2357112 supports Monica Avatar answered Feb 12 '23 10:02

user2357112 supports Monica