以下是斐波那契数列的递归定义:
Fn = Fn1 + Fn2, F1 = 1,F2 = 1.
那么其12项为:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 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