Skip to content

Instantly share code, notes, and snippets.

@larryv
Created March 11, 2012 22:54
Show Gist options
  • Save larryv/2018537 to your computer and use it in GitHub Desktop.
Save larryv/2018537 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby1.9
# Project Euler, Problem 57
#
# It is possible to show that the square root of two can be expressed as an
# infinite continued fraction.
#
# sqrt(2) = 1 + 1/(2 + 1/(2 + 1/(2 + ...))) = 1.414213...
#
# By expanding this for the first four iterations, we get:
#
# 1 + 1/2 = 3/2 = 1.5
# 1 + 1/(2 + 1/2) = 7/5 = 1.4
# 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
# 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
#
# The next three expansions are 99/70, 239/169, and 577/408, but the eighth
# expansion, 1393/985, is the first example where the number of digits in
# the numerator exceeds the number of digits in the denominator.
#
# In the first one-thousand expansions, how many fractions contain a
# numerator with more digits than denominator?
#
# Lawrence Velazquez
# 11 March 2012
class Integer
def digits
self.abs.to_s.length
end
end
def sqrt_2_expand(n)
sum = 1.upto(n - 1).inject(2) {|sum, n| 2 + Rational(1, sum)}
1 + Rational(1, sum)
end
puts(1000.times.count do |n|
expn = sqrt_2_expand(n)
expn.numerator.digits > expn.denominator.digits
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment