## Problem 57: Square root convergents

*Difficulty: Easy

Problem:

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?

How to solve:
Here’s what I got after googling Wiki :
This is continued fraction representation of √2

The first expansions are:

From Continued Fraction (Wiki), we got :

and (*)

For example, with √3
√3 expansions = [1,2,1,2,1,2,1,2,…].

Here is how the table is constructed :

By using those formulas in (*), √2  got this table
√2  expansions [2,2,2,2,2,2…] (with mean a_n – n from 0 to infinity is all 2)
Here’s how it woks:
n = 0
7 = 2*3 + 1 (a_n*h_n_1 + h_n_2)
5 = 2*2 + 1 (a_n*k_n_1 + k_n_2)
n = 1
17 = 2*7+3 (a_n*h_n_1 + h_n_2)
12 = 2*5+2 (a_n*k_n_1 + k_n_2)
and so on
You got the idea

Implementation: Python 2

Initialize:

Generate first 1000 expansions

That’s it .
Solution took 4 ms , which is fast (in my opinion).