Fastest way to determine if an integer's square root is an integer

前端 未结 30 2061
心在旅途
心在旅途 2020-11-22 02:17

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):

  1. I\'ve done it the ea
30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 02:54

    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 true
    • n^2 + 2n + 1 > target > n^2 : you're close, but it's not perfect: return false
    • n^2 - 2n + 1 < target < n^2 : ditto
    • target < 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.

提交回复
热议问题