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):
If you do a binary chop to try to find the "right" square root, you can fairly easily detect if the value you've got is close enough to tell:
(n+1)^2 = n^2 + 2n + 1
(n-1)^2 = n^2 - 2n + 1
So having calculated n^2
, the options are:
n^2 = target
: done, return truen^2 + 2n + 1 > target > n^2
: you're close, but it's not perfect: return falsen^2 - 2n + 1 < target < n^2
: dittotarget < n^2 - 2n + 1
: binary chop on a lower n
target > n^2 + 2n + 1
: binary chop on a higher n
(Sorry, this uses n
as your current guess, and target
for the parameter. Apologise for the confusion!)
I don't know whether this will be faster or not, but it's worth a try.
EDIT: The binary chop doesn't have to take in the whole range of integers, either (2^x)^2 = 2^(2x)
, so once you've found the top set bit in your target (which can be done with a bit-twiddling trick; I forget exactly how) you can quickly get a range of potential answers. Mind you, a naive binary chop is still only going to take up to 31 or 32 iterations.