Project Euler — Problem 57 Solution

Problem

It is pos­si­ble to show that the square root of two can be expressed as an infi­nite con­tin­ued frac­tion.

image

By expand­ing this for the first four iter­a­tions, 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 expan­sions are 99/70, 239/169, and 577/408, but the eighth expan­sion, 1393/985, is the first exam­ple where the num­ber of dig­its in the numer­a­tor exceeds the num­ber of dig­its in the denom­i­na­tor.

In the first one-thou­sand expan­sions, how many frac­tions con­tain a numer­a­tor with more dig­its than denom­i­na­tor?

Solution

// define function to return all the numerator-denominator pairs for the first n expand
let expand n =
    Seq.unfold (fun (num, denom) -> Some((num, denom), (denom*2I+num, denom+num))) (3I, 2I)
    |> Seq.take n

let answer =
    expand 1000
    |> Seq.filter (fun (num, denom) -> num.ToString().Length > denom.ToString().Length)
    |> Seq.length

If you look at the pat­terns 3/2, 7/5, 17/12, 41/29, and so on, it’s easy to spot a pat­tern where the numer­a­tor and denom­i­na­tor of iter­a­tion n can be derived from the iter­a­tion n-1:

Numerator(n) = Numerator(n-1) + 2 * Denominator(n-1)

Denominator(n) = Numerator(n-1) + Denominator(n-1)