Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!news-out.readnews.com!transit4.readnews.com!panix!not-for-mail From: Grant Edwards Newsgroups: comp.lang.python Subject: Re: Storing a very large number Date: Wed, 17 Jul 2013 19:54:57 +0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Lines: 54 Message-ID: References: NNTP-Posting-Host: dsl.comtrol.com X-Trace: reader2.panix.com 1374090897 10045 64.122.56.22 (17 Jul 2013 19:54:57 GMT) X-Complaints-To: abuse@panix.com NNTP-Posting-Date: Wed, 17 Jul 2013 19:54:57 +0000 (UTC) User-Agent: slrn/1.0.1 (Linux) Xref: csiph.com comp.lang.python:50802 On 2013-07-17, Hasit Mistry 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 76912142205156893736567110721938151873066848551250079691933197504698382687850162519363381241341072061717399276279446152783228293733394674915106506777652714586583257515548935662783041098025828748644732150180263384738920337734332306732579704813309358353325051464419679305008247276777590803598706960718369750920313818346498676991944268444745266147723127330821117640028009756028827267657249563468436491879452209207125425662579803287297238987286648041733328816128585346936668110411776730224052535307657062833269810807032506745274610105341051559960125927107837478566295005327614374967849408928939897747893587527876150286368001L >>> x = int(math.pi * 10**15) ** 40 >>> sys.getsizeof(x) 288 >>> math.log10(x) 619.8859949077654 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: >>> str(x)[209] '3' -- Grant Edwards grant.b.edwards Yow! If elected, Zippy at pledges to each and every gmail.com American a 55-year-old houseboy ...