Ruby - Is A Number A Perfect Square?
Don’t rely on Math::sqrt
.
It will let you down on very large numbers.
If you want to check if a very large number is a perfect square, find the nearest square with this binary search method. Then square the result and check if it matches your original number.
def approx_sqrt(num)
low = 1
high = num
while high > low + 1
mid = (high + low)/2
if mid ** 2 <= num
low = mid
else
high = mid
end
end
return low
end