Project Euler

Project Euler Problem 57

steloflute 2012. 5. 28. 00:01

Problem 57

21 November 2003


 

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 in C#

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace Euler {
    static class Problem57 {
        public static void run() {
            BigInteger n1 = 3;
            BigInteger d1 = 2;
            BigInteger n2 = 7;
            BigInteger d2 = 5;
            var count = 0;
            for (var i = 3; i <= 1000; i++) {
                var nNew = 2 * n2 + n1;
                var dNew = 2 * d2 + d1;
                if (nNew.ToString().Length > dNew.ToString().Length) count++;

                //Console.WriteLine(nNew + " " + dNew);
                //Console.ReadKey();
                n1 = n2;
                d1 = d2;
                n2 = nNew;
                d2 = dNew;
            }
            Console.WriteLine(count);
        }
    }
}

 

'Project Euler' 카테고리의 다른 글

Project Euler Problem 211  (0) 2012.05.28
Project Euler Problem 58  (0) 2012.05.28
Project Euler Problem 56  (0) 2012.05.28
Project Euler Problem 55  (0) 2012.05.28
Project Euler Problem 53  (0) 2012.05.28