OVREVIEW
1000-digit Fibonacci number
- 递推与递归
- 高精度
The Fibonacci sequence is defined by the recurrence relation:Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
1.大整数加法
将两个数组循环相加——用指针将数组的地址作为函数参数传递到函数中,通过交换二维数组第一个下标交换数组地址
/*思路:大整数加法 + 循环使用两个变量求fib数列
1.将大整数加法封装在一个函数中
2.循环使用两个变量(数组)求斐波那契数列项
3.当出现某一项大于1000时,输出项数结束循环
*/
#include<iostream>
using namespace std;
//1.将大整数加法封装在一个函数中
void func(int *n1, int *n2){
//注意:初始的n2可能比n1短,需要首先更新答案的长度
n2[0] = n1[0];
for(int i = 1; i <= n2[0]; ++i){
n2[i] += n1[i];
if(n2[i] > 9){
n2[i + 1] += n2[i] / 10;
n2[i] %= 10;
if(i == n2[0]){
n2[0]++;
}
}
}
}
int main(){
//等价于开辟两个长度为1005的数组,用于存储斐波那契数列项
int num[2][1005] = {{1, 1}, {1, 1}};
int a = 0, b = 1;
//2.循环使用两个数组求斐波那契数列项
for(int i = 3; 1; ++i){
//数组地址作为函数参数传递
func(num[a], num[b]);
//3.当出现某一项大于1000时,输出项数结束循环
if(num[b][0] >= 1000){
cout << i << endl;
break;
}
//通过交换a,b间接交换两个数组的地址
swap(a, b);
}
return 0;
}
注意:理解语句
n2[0] = n1[0];
tips:文章部分内容参考算法刷题课程,题解图示内容及代码根据老师课程、以及自己对知识的理解,进行二次整理和部分补充,仅供学习参考使用,不可商业化。