Question

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.

Was it helpful?

Solution

There is a simple way to calculate the square root of an integer, which results in an integer:

  1. To find the square root of a number, set M and P to that number.
  2. Then calculate (M+P/M)/2, rounding each division down.
  3. If M equals or is less than the result, use M as the square root; otherwise, set M to the result and repeat this process at step 2.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top