I\'m looking for the fastest way to determine if a long
value is a perfect square (i.e. its square root is another integer):
Project Euler is mentioned in the tags and many of the problems in it require checking numbers >> 2^64
. Most of the optimizations mentioned above don't work easily when you are working with an 80 byte buffer.
I used java BigInteger and a slightly modified version of Newton's method, one that works better with integers. The problem was that exact squares n^2
converged to (n-1)
instead of n
because n^2-1 = (n-1)(n+1)
and the final error was just one step below the final divisor and the algorithm terminated. It was easy to fix by adding one to the original argument before computing the error. (Add two for cube roots, etc.)
One nice attribute of this algorithm is that you can immediately tell if the number is a perfect square - the final error (not correction) in Newton's method will be zero. A simple modification also lets you quickly calculate floor(sqrt(x))
instead of the closest integer. This is handy with several Euler problems.