Skip to content

Instantly share code, notes, and snippets.

@srinivasreddy
Created January 17, 2012 08:44
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 srinivasreddy/1625699 to your computer and use it in GitHub Desktop.
Save srinivasreddy/1625699 to your computer and use it in GitHub Desktop.
euler problem 57
"""
It is possible to show that the square root of two can be expressed as an infinite continued fraction.
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?
"""
import sys
from fractions import Fraction
"""
1+1/2 = 3/2
1+1/(2+1/2) = 7/5
1+1/(2+1/(2+1/2)) = 17/12
so i tried to represent 1/(2+1/2) recurrence as a function!!!
"""
def Irrational(counter):
if counter==1:
return Fraction(1,2)
return Fraction(1,1)/(Fraction(2,1) + Irrational(counter=counter-1))
if __name__ =="__main__":
sys.setrecursionlimit(1500)
number=0
for counter in range(1,1001):
##we need to add 1 to irrational part.
fraction = Fraction(1,1)+Irrational(counter)
if(len(str(fraction.numerator))>len(str(fraction.denominator))):
number=number+1
print number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment