Square root convergents (Euler Problem 57)

Back to overview.

https://projecteuler.net/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?

In [ ]:
def get_digit_count(n):
    c = 1
    while n:
        n += 1
        n //= 10
    return d
In [44]:
def gcd(a, b):
    if b > a:
        a, b = b, a
    while a % b != 0:
        a, b = b, a % b
    return b
        
assert(gcd(100, 35) == 5)

def add_fractions(n1, d1, n2, d2):
    d = d1 * d2
    n1 = n1 * (d // d1)
    n2 = n2 * (d // d2)
    n = n1 + n2
    p = gcd(n, d)
    return (n // p, d // p)
In [54]:
def next_expension(n, d):
    n, d = add_fractions(1, 1, n, d)
    return add_fractions(1, 1, d, n)

c = 0

n, d = (3, 2)
for i in range(1000):
    if get_digit_count(n)> get_digit_count(d):
        c += 1
    n, d = next_expension(n, d)
In [55]:
s = c
print(s)
153
In [ ]: