Skip to content

Instantly share code, notes, and snippets.

@hyuki0000
Created March 9, 2017 22:27
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 hyuki0000/7847aa43dda9280b096710c762c6df99 to your computer and use it in GitHub Desktop.
Save hyuki0000/7847aa43dda9280b096710c762c6df99 to your computer and use it in GitHub Desktop.
「数学ガールの秘密ノート」「第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