2的平方根可以被表示爲無限延伸的分數:
2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
將其前四次迭代展開,我們得到:
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...
接下來三次迭代的展開是99/70, 239/169, and 577/408, 但是第八次迭代的展開, 1393/985, 是第一個分子的位數超過分母的位數的例子。
在前1000次迭代的展開中,有多少個的分子位數超過分母位數?
import java.math.BigInteger;
public class Problem57
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();
System.out.print("answer: ");
howmany();
long end = System.currentTimeMillis();
System.out.print("time: ");
System.out.println(end - start);
}
static void howmany()
{
int sum = 0;
//不能用 int,不然越界~~
BigInteger array[] = {BigInteger.ONE,BigInteger.valueOf(2)};
for (int i = 1; i < 1000; i++)
{
array = jisuan(array, i);
BigInteger zi = array[0].add( array[1] );
if ( (zi + "").length() > (array[1] + "").length() )
{
sum++;
}
}
System.out.println(sum);
}
static BigInteger [] jisuan(BigInteger array[], int n)
{
BigInteger t = array[1];
array[1] = array[1].multiply(BigInteger.valueOf(2)).add( array[0] );
array[0] = t;
return array;
}
}
answer: 153
time: 221