You are on the Home/Other Tutorials/Project Euler/Problem 57 page
Google
Web This Site

Project Euler - Problem 57

More about Project Euler.

Problem description

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?

Solution

The easiest way to solve this is to not worry about how each expansion is calculated but to simply look at the result, and more specifically, the individual numerators and denominators.  The fractions are:

3
-
2
7
-
5
17
--
12
41
---
29
99
---
70
239
-----
169
577
-----
408
1393
-------
 985

A quick inspection shows that the numerators form a series with Ni = 2*Ni-1 + Ni-2 for i 3 and the denominators form the same series with Di = 2*Di-1 + Di-2 for i 3.

With this information, the solution becomes rather trivial.  The only issue is that the numbers get so large that not even the Double data type in Excel is large enough.  So, we have to use the Large Number Arithmetic module.

In the code below, the 2 arrays Num and Denom hold the last 2 values of the numerators and denominators respectively.  The index, Idx, points to the (i-2)th value, the one that can be replaced with the current calculations.

Sub Euler057()
    Dim Num(1) As String, Denom(1) As String, ExpNbr As Integer, Idx As Integer, _
        Rslt As Long, ProcTime As Single
    ProcTime = Timer
    Num(0) = "3": Num(1) = "7"
    Denom(0) = "2": Denom(1) = "5"
    Idx = 0
    For ExpNbr = 3 To 1000
        Num(Idx) = LargeAdd(LargeMult(Num((Idx + 1) Mod 2), "2"), Num(Idx))
        Denom(Idx) = LargeAdd(LargeMult(Denom((Idx + 1) Mod 2), "2"), Denom(Idx))
        If Len(Num(Idx)) > Len(Denom(Idx)) Then Rslt = Rslt + 1
        Idx = (Idx + 1) Mod 2
        Next ExpNbr
    Debug.Print Rslt, Timer - ProcTime
    End Sub