以下是斐波那契数列的递归定义:
F n = F n1 + F n2, F 1 = 1,F 2 = 1.
那么其12项为:
F 1 = 1
F 2 = 1
F 3 = 2
F 4 = 3
F 5 = 5
F 6 = 8
F 7 = 13
F 8 = 21
F 9 = 34
F 10 = 55
F 11 = 89
F 12 = 144
因此第12项,F12,是第一个包含三位数字的项。
斐波那契数列中第一个包含1000位数字的项是第几项?
import java.math.BigInteger;
public class Problem25
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();
System.out.print("answer: ");
BigInteger a1 = BigInteger.ONE, a2 = BigInteger.ONE;
for (int i = 2; ; i++)
{
if ((a2+"").length() == 1000)
{
System.out.println(i);
break;
}
BigInteger temp = a2;
a2 = a2.add(a1);
a1 = temp;
}
long end = System.currentTimeMillis();
System.out.print("time: ");
System.out.println(end - start);
}
}
answer: 4782
time: 575