Last active
October 17, 2017 19:35
-
-
Save purplejacket/48400ff490cd4b15fb0076f91678efb9 to your computer and use it in GitHub Desktop.
Find square root using Newton's Method -- Ruby version (we use a trick to get a good starting seed value)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # https://www.codewars.com/kata/square-root-without-using-library-math | |
| # the challenge stipulates: don't require any libs, don't use ** operator (exponentiation) | |
| # the challenge also says all inputs will already be perfect squares of integers | |
| # This code works for very large integers as well as small ones | |
| def square_root_me(num) | |
| start = num.to_s(2); start = start[0,(start.length/2)].to_i(2) | |
| retval = start | |
| for i in 0..10000 do | |
| # (Note: i is not used; we want to avoid an infinite loop if we're given bad input) | |
| retval = ((retval + num/retval)/2).to_i | |
| return retval if retval*retval == num | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment