Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
「数学ガールの秘密ノート」「第189回 九章算術の研究、もっと」より https://bit.ly/girlnote189
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