当前位置:首页 » Project Euler » 详细页

Square root convergents 题号:57 难度: 5 中英对照

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

由题可知,数列为: $$ \frac{n_k}{d_k}: \frac{3}{2}, \frac{7}{5}, \frac{17}{12}, \frac{41}{29}, \frac{99}{70}, \frac{239}{169}, \frac{577}{408}, ... $$ 从中我们可以发现: $$ n_{k+1} = n_k + 2d_k $$ $$ d_{k+1} = n_k + d_k $$ 利用此递推式进行循环即可以暴力法得到解。

Code


import java.math.BigInteger;

public final class p057 {

    public static void main(String[] args) {
        long start = System.nanoTime();
        long result = run();
        long end = System.nanoTime();
        System.out.println(result);
        System.out.println((end - start) / 1000000 + "ms");
    }

    public static long run() {        
        BigInteger n = BigInteger.valueOf(3);
        BigInteger d = BigInteger.valueOf(2);
        BigInteger TWO = BigInteger.valueOf(2);
        int count = 0;
        int i=1;
        while(i<=1000){            
            if(n.toString().length()>d.toString().length()) count++;
            BigInteger tmp = n;
            n = tmp.add(d.multiply(TWO));
            d = tmp.add(d);
            i++;
        } 
        return count;
    }
}
153
126ms