欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

斐波那契数列poj(矩阵快速幂)

程序员文章站 2022-06-04 12:21:24
...

Fibonacci

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18040   Accepted: 12541

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

斐波那契数列poj(矩阵快速幂).

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

斐波那契数列poj(矩阵快速幂).

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

斐波那契数列poj(矩阵快速幂).

Source

Stanford Local 2006

 

       以前写斐波那契数列用递推公式写,对以前的n不大,但碰见n比较大的时候就会超时,比较尴尬,这个时候矩阵快速幂来了。

  1. 首先构造f1,f0矩阵(此题比较特殊,不用构造)
  2. 然后类似于1构造一个单位矩阵(单位矩阵就是那么一个矩阵 这个矩阵乘以任何一个矩阵都等于他乘的那个矩阵)sec
  3. 如下图,构造矩阵fir
  4. 然后判断n如果n<2直接输出,否则fir的(n-1)次方,在这个过程中注意取余操作;然后再乘以初始矩阵(此题比较特殊,你会发现直接输出乘方后的pos[0][0]就行了。
  5. 第一次写这个东西,多多指教,代码很烂。
斐波那契数列poj(矩阵快速幂)

 

 

 

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
struct mat
{
    int pos[2][2];
    mat()
    {
        memset(pos,0,sizeof(pos));
    }
};
mat fir,sec;
mat Cheng(mat a,mat b)
{
    mat c;
    for(int i=0;i<2;i++)
        for(int j=0;j<2;j++)
            for(int k=0;k<2;k++)
            c.pos[i][j]=(c.pos[i][j]+a.pos[i][k]*b.pos[k][j])%10000;
    return c;
}
void mul(mat b,int n)
{
    while(n>0)
    {
        if(n%2==1)
            sec=Cheng(sec,b);
        n=n/2;
        b=Cheng(b,b);
    }
}
int main()
{
    int n;
    while(scanf("%d",&n)&&n>=0)
    {
    if(n==0)
        cout<<0<<endl;
    else if(n==1)
        cout<<1<<endl;
    else
    {
        sec.pos[1][1]=1,sec.pos[0][0]=1,sec.pos[0][1]=0,sec.pos[1][0]=0;
        fir.pos[0][0]=1,fir.pos[0][1]=1,fir.pos[1][0]=1,fir.pos[1][1]=0;
        mul(fir,n-1);
        cout<<sec.pos[0][0]<<endl;
    }
    }
    return 0;
}

 

相关标签: 快速幂