Storing big numbers over 9,000 digits in Python

file, integer, long-integer, python

Solution

Python can store arbitrarily long integers using the `long` type and even lets you specify `long` literals by appending an `L` to them (e.g. `0L` is a `long` zero, as opposed to just `0` which is an `int`). Even better, it automatically "promotes" numbers from `int`s to `long`s when the result of a calculation is too large to be represented by an `int`. `long` is a full-fledged numeric type and is compatible with all Python numeric operations.

If you need more than integers, then you want the `decimal` module, which features a `Decimal` type that provides real numbers of arbitrary size and precision, without the issues inherent to binary floating-point representations.

The downside of both `long` and `Decimal` is that they are slower than `int` and `float`, respectively, because the latter have native hardware support. But doing math on large numbers somewhat slowly beats not being able to use such numbers at all.

As for size, `int` objects are 12 bytes in 32-bit Python. This seemingly large size for what is internally a 32-bit quantity is due to Python's "everything's an object" approach. (I believe, but don't quote me, that there's 4 bytes for the value, 4 bytes for a pointer from the instance to the type, and 4 bytes for a reference counter, which is used to determine when an object can be garbage-collected. These fields may be larger on 64-bit versions of Python.)

The size of a `long` varies, as they vary based on the number (plus object overhead), but the size of any `long` value can be determined using `sys.getsizeof()`.

Problem

I'm planning to use very big numbers in Python, but wonder if Python can handle very big numbers. The numbers are going to have up to 3,000 zeros. And, how much bytes does a 1 with 3,000 zeros use? Third question, how can I save a number as integer into a file with Python without having to str() it?

Original source