Created
March 9, 2017 22:27
-
-
Save hyuki0000/7847aa43dda9280b096710c762c6df99 to your computer and use it in GitHub Desktop.
「数学ガールの秘密ノート」「第189回 九章算術の研究、もっと」より https://bit.ly/girlnote189
This file contains 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
def sqrtn(s) | |
a = 0 | |
p = 0 | |
while not (0 <= (s / 10**p) and (s / 10**p) < 100) do | |
p += 2 | |
end | |
while p >= 0 | |
b = 9 | |
while (s / 10**p) < b * (20 * a + b) do | |
b -= 1 | |
end | |
s = s - b * (20 * a + b) * 10**p | |
a = 10 * a + b | |
p -= 2 | |
end | |
return a | |
end | |
def test_sqrtn | |
(0..99999).each do |n| | |
a = sqrtn(n) | |
b = Math::sqrt(n).to_i | |
if a == b | |
puts "OK: sqrtn(#{n}) is #{a}. (#{Math::sqrt(n)})" | |
else | |
puts "ERROR: sqrtn(#{n}) is #{a}, but Math::sqrt(n).to_i is #{b} (#{Math::sqrt(n)})" | |
abort | |
end | |
end | |
end | |
puts sqrtn(55225) | |
puts sqrtn(3972150625) | |
puts sqrtn(2_00_00_00_00_00_00_00_00) | |
# test_sqrtn |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment