Skip to content

Instantly share code, notes, and snippets.

@tompng
Created March 16, 2024 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tompng/ee2be24be3cd5b56d636f4dba3f57c0d to your computer and use it in GitHub Desktop.
Save tompng/ee2be24be3cd5b56d636f4dba3f57c0d to your computer and use it in GitHub Desktop.
class Integer
def self.isqrt(n)
return 0 if n == 0
return 1 if n < 4
shift = [n.bit_length / 4, 1].max
x = Integer.isqrt(n >> (shift * 2))
x = (x << (shift - 1)) + (n >> (shift + 1)) / x
xx = x * x
while xx > n
xx -= 2 * x - 1
x -= 1
if xx > n
p :unreachable?
end
end
x
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment