Skip to content

Instantly share code, notes, and snippets.

@justinwsmith
Last active January 1, 2016 02:19
Show Gist options
  • Save justinwsmith/8078654 to your computer and use it in GitHub Desktop.
Save justinwsmith/8078654 to your computer and use it in GitHub Desktop.
An implementation of Integer square root (needed when working with very large numbers).
# Copyright (c) 2014 Justin W. Smith <justin.w.smith@gmail.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
################################
class Integer
def isqrt
return 0 if zero?
return 1 if self == 1
return nil if self < 0
x_k = next_x_k = (self >> 1)
begin
x_k = next_x_k
next_x_k = (x_k + self/x_k) >> 1
end until (x_k - next_x_k) <= 0
return x_k
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment