以下是斐波那契数列的递归定义:
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位数字的项是第几项?
public class Test {
public static void main(String[] args) {
int[] fib = new int[1000];
int[] answer = new int[1000];
int[] temp = new int[1000];
fib[0] = answer[0] = 1; // 存储第n项的结果(逆序)
int num = 2; // 初始为2项
while (true) {
temp = answer.clone(); // 记录fib前一项
for (int i = 0; i < 1000; i++) {
answer[i] += fib[i];
}
fib = temp.clone();
for (int i = 0; i < 1000 - 1; i++) {
if (answer[i] >= 10) {
answer[i + 1]++;
answer[i] = answer[i] % 10;
}
}
num++;
if (answer[999] != 0) {
break;
}
}
System.out.println(num);
}
}