Poj3070 Fibonacci (矩阵快速幂)

11 篇文章 0 订阅
4 篇文章 0 订阅

原题点这里 Time Limit: 1000MS Memory Limit: 65536K

Description

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.

Input

The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.

Output

For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).

Sample Input

0
9
999999999
1000000000
-1

Sample Output

0
34
626
6875

Hint

As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by

这里写图片描述

Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

这里写图片描述

题目大意(百度机翻

在斐波纳契数列的整数序列,F0 = 0,F1 = 1,和Fn = 1 + Fn Fn−2 n≥2。

例如,斐波那契数列的前十项是:0, 1, 1,2, 3, 5,8, 13, 21,34,…

斐波那契数列的另一个公式是

这里写图片描述

给定一个整数n,你的目标是计算FN的最后4个数字。

输入输入测试文件将包含多个测试用例。

每个测试案例是由单独的一行包含N(0≤N≤1000000000)。

文件结尾是由一个单一的行数−1表示。输出对于每个测试用例,输出FN的最后四个数字。

如果FN的最后四个数字都为零,则输出“0”;

否则,省略任何前导零(即,输出Fn mod 10000)。

样本输入
0
9
999999999
1000000000
- 1

示例输出
0
34
626
6875

纯模板

代码

#include<cstdio>
#include<cstdlib>
#include<cstring>
#define Mod 10000
struct node
{
    int v[3][3];
    int m,l;
};
node get_mul(node a,node b)
{
    node c;
    c.m=a.m;c.l=b.l;
    for(int i=1;i<=c.m;i++)
      for(int j=1;j<=c.l;j++)
      {
          c.v[i][j]=0;
          for(int k=1;k<=a.l;k++)
              c.v[i][j]=(c.v[i][j]+a.v[i][k]*b.v[k][j])%Mod;
      }
    return c;
}
int main()
{
    int n;
    while(1)
    {
        scanf("%d",&n);
        if(n==0) {printf("0\n");continue;}
        if(n==-1) break;
        node a,b,c;
        a.m=a.l=2,a.v[1][1]=1,a.v[1][2]=1,a.v[2][1]=1,a.v[2][2]=0;
        b.m=b.l=2,b.v[1][1]=1,b.v[1][2]=0,b.v[2][1]=0,b.v[2][2]=1;
        c.m=2,c.l=1,c.v[1][1]=1,c.v[2][1]=0;
        n--;
        while(n)
        {
            if(n&1) b=get_mul(a,b);
            a=get_mul(a,a);
            n>>=1;
        }
        b=get_mul(b,c);
        printf("%d\n",b.v[1][1]);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值