1000-digit Fibonacci number
The Fibonacci sequence is defined by the recurrence relation:
Hence the first 12 terms will be:
The 12th term,
, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits
1000位斐波那契数
斐波那契数列是按如下递归定义的数列:
因此斐波那契数列的前12项分别是:
在斐波那契数列中,第一个包含三位数字的是第12项
。
在斐波那契数列中,第一个包含1000位数字的是第几项?
这个题目求的是1000位数字是第几项,那么问题来了,没有类型可以存的下1000的数字,那么只有每位存进数组进行相加,那么这个题就和第13题 就差了太多了,都需要用大整数加法;
大整数加法,0位存当前数的位数,低位存低位,高位存高位(因为方便进位);
这个题我采用一个滚动数组法,只用开2个存储空间,所谓能省则省,如何实现的,来看代码:
#include <stdio.h> int main() { int f[2][1005] = {0}; f[0][0] = f[0][1] = f[1][0] = f[1][1] = 1;//初始化第一项第二项 int n = 1;//因为最开始n会++所以直接赋值为1,从第二项开始 while (f[n % 2][0] < 1000) {//因为第0位存的位数,可以直接判断循环结束条件 n++; f[n % 2][0] = f[(n - 1) % 2][0]; for (int i = 1, I = f[(n - 1) % 2][0]; i <= I; i++) { f[n % 2][i] = f[(n - 1) % 2][i] + f[(n - 2) % 2][i];//求得的当前项去覆盖下次不用的项 if (f[n % 2][i] < 10) continue; f[n % 2][i + 1] += f[n % 2][i] / 10; f[n % 2][i] %= 10; f[n % 2][0] += (i == I); } } printf("%d\n", n + 1);//因为我相当于从第0项开始,所以最后需要加1 return 0; }
最终答案:4782