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
Screen Shot 2016-07-13 at 8.25.12 PM

The first expansions are:
Screen Shot 2016-07-13 at 8.26.15 PM

From Continued Fraction (Wiki), we got :
Screen Shot 2016-07-13 at 8.34.48 PM
and (*)
Screen Shot 2016-07-13 at 8.35.28 PM
For example, with √3
√3 expansions = [1,2,1,2,1,2,1,2,…].
Screen Shot 2016-07-13 at 8.36.59 PM
Here is how the table is constructed :
Screen Shot 2016-07-13 at 8.37.34 PM
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) Screen Shot 2016-07-13 at 8.47.32 PM
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:
Screen Shot 2016-07-13 at 8.53.39 PM
Generate first 1000 expansions
Screen Shot 2016-07-13 at 8.54.34 PM
That’s it .
Solution took 4 ms , which is fast (in my opinion).

Advertisements