Skip to content

Instantly share code, notes, and snippets.

@katoy
Last active August 29, 2015 14:14
Show Gist options
  • Save katoy/c3bcd70eac497ebfed55 to your computer and use it in GitHub Desktop.
Save katoy/c3bcd70eac497ebfed55 to your computer and use it in GitHub Desktop.
ruby で円周率
# See http://keibakuroku.jp/category/brain-teaser
def pi_1(len)
count = 0
k, a, b, a1, b1 = 2, 4, 1, 12, 4
while TRUE
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p * a + q * a1, p * b + q * b1
# Print common digits
d = a / b
d1 = a1 / b1
while d == d1
print d
$stdout.flush
print "." if count == 0
count += 1
return if count > len
a, a1 = 10 * (a % b), 10 * (a1 % b1)
d, d1 = a / b, a1 / b1
end
end
end
len = 100
len = ARGV[0].to_i if ARGV.size == 1
pi_1(len)
puts
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
# See http://keibakuroku.jp/category/brain-teaser
def pi_2(len)
b = (10 ** len).freeze
b2 = (b << 1).freeze
pi = (len * 8 + 1).step(3, -2).inject(b) {|a, i| (i >> 1) * (a + b2) / i} - b
puts "3.#{pi}"
end
len = 100
len = ARGV[0].to_i if ARGV.size == 1
pi_2(len)
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment