Sam Kong wrote:
> Hello,
> 
> I'm solving a math problem in Ruby.
> I need to determine if a number is a perfect square.
> If the number is small, you may do like the following.
> 
> def perfect_square? n
>   sqrt = n ** 0.5
>   sqrt - sqrt.to_i == 0
> end
> 
> But Float number has limitation on precision.
> Thus the function won't work correctly for big numbers like
> (123456789123456789).
> 
> How would you solve such a case?
> It should be fast as well as correct because I will use it repeatedly.

Easy: compare integers rather than floats.

x = 123456789123456789

sqrt = Math::sqrt(x)
p(x == sqrt.floor**2)

-- 
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407