【欧拉计划】Q10:1000-digit Fibonacci number

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:文章部分内容参考算法刷题课程,题解图示内容及代码根据老师课程、以及自己对知识的理解,进行二次整理和部分补充,仅供学习参考使用,不可商业化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值