以下是斐波那契數列的遞歸定義:
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