Fibonacci

题目

        In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

An alternative formula for the Fibonacci sequence is

.

Given an integer n, your goal is to compute the last 4 digits of Fn.

中文

        在Fibonacci整数序列中,F0 = 0, F1=1,和Fn = Fn−1 + Fn−2为n例如,Fibonacci序列的前十个项是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

Fibonacci序列的另一个公式是

.

        给定整数n,您的目标是计算Fn.

输入

        输入测试文件将包含多个测试用例。每个测试用例由包含n(其中0≤)的一行组成。n(≤1,000,000,000)。文件的结尾由包含数字−1的一行表示.

输出

        对于每个测试用例,打印˚F ñ。如果最后四位数˚F ñ均为零,打印‘0’;否则,省略任何前导零(即打印)。ñ10000)。

样本输入

0
9
999999999
1000000000
-1

样本输出

 0
34
626
6875

暗示 

       作为提醒,矩阵乘法是相联的,并给出了两个2×2矩阵的乘积

.

另外,请注意,将任意2×2矩阵提升到第0次方会给出恒等矩阵:

.

 题目链接:Fibonacci

思路

    求矩阵,输出结果矩阵res的第二行第一列的数即为所求

 代码

#include <iostream>
#include <algorithm>
#include <memory.h>
using namespace std;
typedef long long ll;
#define mod 10000
ll n;
const int N=2;
ll tmp[N][N];
void mul(ll a[][N],ll b[][N],ll n)
{
    memset(tmp,0,sizeof(tmp));
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            for(int k=0;k<n;k++)
                tmp[i][j]=(tmp[i][j]+a[i][k]*b[k][j])%mod;
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            a[i][j]=tmp[i][j];
}
ll res[N][N];
void Pow(ll a[][N],ll n)
{
    memset(res,0,sizeof res);
    for(int i=0;i<N;i++)
        res[i][i]=1;
    while(n){
        if(n&1)
            mul(res,a,N);
        mul(a,a,N);
        n>>=1;
    }
}
int main()
{
    while(cin>>n&&n!=-1){
    ll vis[N][N]={{1,1},{1,0}};
    Pow(vis,n);
    cout<<res[1][0]<<endl;
    }
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

int 我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值