Simplifiy your problem, using a bit of math.
Note that sqrt(a*b) = sqrt(a) * sqrt(b)
(for real, positive numbers at least).
So, any number larger than, say, 10^100, divide by 10^100. That's a
, and the result of the division is b
, so that your original number = a * b
.
Then use the square root of 10^100 (= 10^50), multiply that by the square root of b
, and you have your answer.
With your example:
import math
x = 10**309
a = 1e100
b = 1e209 # Note: you can't calculate this within Python; just use plain math here
y = 1e50 * math.sqrt(1e209)
Example for a not-so-round number:
x = 3.1415 * 1e309
a = 1e100
b = 3.1415e209 # Again, just subtract the exponent: 309 - 100
y = 1e50 * math.sqrt(3.1415e209)
Or for an integer that's not a power of 10, fully written out:
x = 707070
x = 70.707 * 1e4 # note: even number in exponent
x = 70.707e4
a = 1e2 # sqrt(1e2) = 1e1 = 10
b = 70.707e2
y = 10 * sqrt(70.707e2)
A few notes:
Python handles ridiculously large integer numbers without problems. For floating point numbers, it uses standard (C) conventions, and limits itself to 64 bit precision. You almost always get floating point numbers when taking a square root of something.
1e309
means 10**309
, and 3.1415e209
means 3.1415 * 10**209
. This is a standard programming convention.
math.sqrt
returnsinf
for anything larger than 10^308 – Interjacentsqrt
and various functions inmath
are based on the math C library. That library normally only handles up to the limit of a C double, usually a 64 bit floating point number. 10^308 is the (absolute) maximum of a 64 bit floating point number (following the IEEE 754 standard). – Hypognathousgmpy2
is, I believe, the state of the art for dealing with truly humongous numbers in Python (I'm biased because I originated its precursorgmpy
, but haven't been active in either for a long while -- the current maintainers have done an awesome job). Try it out! – Wolbromgmpy2.isqrt
can calculate the integer square root of a 1,000,0000 digit number in less than 25 ms. – Yimisqrt
calculates the integer square root.sqrt
returns a multiple precision floating point value but you can increase the precision to any number of bits. – Yim