Last active
December 18, 2015 03:08
-
-
Save mbrenig/5715776 to your computer and use it in GitHub Desktop.
Generate list continued fractions for square root of number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import sqrt | |
def gcd(a,b): | |
while a != 0: | |
a, b = b % a, a | |
return b | |
def sqrt_cf(D): | |
A = [] | |
b = 0 | |
c = 1 | |
first_term = True | |
ta,tb,tc = (0,0,0) | |
while True: | |
A_n = int( (sqrt(D) + b) / c ) | |
A.append(A_n) | |
# Recurence set up by re-arranging: A_n+1 = 1 / ( ((sqrt(D)+b)/c) - A_n ) | |
# and noting that the denominator is divisible by c | |
(b,c) = ( (A_n*c-b), | |
(D - (b-A_n*c)**2)/c ) | |
if first_term: | |
first_term = False | |
tb,tc = b,c | |
elif b==tb and c==tc: | |
break | |
return A | |
D = int(raw_input("D = ")) | |
try: | |
print "%s\t%s" % (D, sqrt_cf(D)) | |
except: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment