Storing a very large number
invalid at invalid.invalid
Wed Jul 17 21:54:57 CEST 2013
On 2013-07-17, Hasit Mistry <hasitnm at lavabit.com> wrote:
> I came across a problem that requires me to store a very large number
> (say >10^100). How do I do it efficiently?
First you must define "efficient".
If you want to store the least number of bytes, and all you need to do
is store the number (you don't need to manipulate it numerically, then
storing it as an ascii string in exponential notion might be the
smallest and fastest:
veryLargeNumber = "10^100"
That's only 27 bytes (CPython 2.7 on Linux).
If you do need to do math on it, then what's wrong with this?
veryLargeNumber = 10**100
That takes 58 bytes, but is much simpler for doing calculations.
> And also, how do I select a particular number (say 209th) from that very
> large number?
I don't know what you mean by "a particular number". Do you mean you
want to know the value of a particular digit when it's representing in
a partuclar base (e.g. base 10)?
Does this do what you want?
First, we'll generate a number with a lot of digits:
>>> int(math.pi * 10**15) ** 40
>>> x = int(math.pi * 10**15) ** 40
It has 600+ digits and requires 288 bytes to store.
Counting from the left-hand side, starting '7' as digit 0, the 209th
digit in the base-10 representation is:
Grant Edwards grant.b.edwards Yow! If elected, Zippy
at pledges to each and every
gmail.com American a 55-year-old
More information about the Python-list