Skip to content

Instantly share code, notes, and snippets.

@antimon2
Created May 2, 2012 03:22
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 antimon2/2573349 to your computer and use it in GitHub Desktop.
Save antimon2/2573349 to your computer and use it in GitHub Desktop.
Integer#isqrt - sqrt in Integer precision
class Integer
def isqrt
return 0.0/0 if self < 0
return self if self < 2
return 1 if self < 4
# === Newton's Method (in Integer precision) ===
n = self.div 2 # self / 2
while n * n > self
on = n
n = (n * n + self).div(2 * n)
break if n == on
end
n
end
end
### v- to Enable the Following for Efficiency
# class Fixnum
# def isqrt
# return Math.sqrt(self).floor if 0 <= self && self < 2**53
# super
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment