I'm trying to calculate the square root of a really big number in Ruby. The problem I have is that the Math.sqrt function looks like this
sqrt(numeric) → float
If I feed it a really big number, it will give me FloatDomainError: Infinity.
What is the best way to get sqrt()
to return a BigNum? Is there perhaps a gem for this or will I have to write my own function to calculate the square root?
In that case, what is the easiest way to go about doing this? Taylor series? The square roots of the numbers will always be integers.
There is a simple way to calculate the square root of an integer, which results in an integer:
This approach may be inefficient for big numbers, though, so try it and see.
EDIT:
Here's the Ruby implementation:
def mysqrt(x)
return 0 if x==0
m=x
p=x
loop do
r=(m+p/m)/2
return m if m<=r
m=r
end
end