poj 3070 Fibonacci 【矩阵快速幂】

来源:互联网 发布:电脑端扫描仪软件 编辑:程序博客网 时间:2024/06/04 00:51
Fibonacci
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11260 Accepted: 8007

Description

In the Fibonacci integer sequence, F0 = 0, F1 = 1, andFn = Fn − 1 + Fn − 2 forn ≥ 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 ofFn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., printFn mod 10000).

Sample Input

099999999991000000000-1

Sample Output

0346266875

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:

.

Source

Stanford Local 2006
 
思路:
 
         其实矩阵快速幂与一般的实数的快速幂的方法一模一样,只不过就是在相乘的时候又设了一个函数,也就是矩阵相乘,带有返回值的函数!在矩阵相乘的时候,用第一个矩阵的某一行的元素与第二个矩阵某一列的元素对应相乘相加就OK了!
 
代码:
 
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int n;struct Maxtri//建立矩阵 {int r,c;int a[5][5];};Maxtri ori,res;//ori是起始矩阵(相当于底数),res是结果矩阵(相当于sum) void init(){memset(res.a,0,sizeof(res.a));for(int i=1;i<=2;i++)//初始化结果矩阵 res.a[i][i]=1;ori.a[1][1]=1;ori.a[1][2]=1;//初始化起始矩阵 ori.a[2][1]=1;ori.a[2][2]=0;}Maxtri maxtri(Maxtri x,Maxtri y)//计算两个矩阵的乘积 {Maxtri z;memset(z.a,0,sizeof(z.a));for(int i=1;i<=2;i++){for(int k=1;k<=2;k++){if(x.a[i][k]==0)continue;//剪枝 for(int j=1;j<=2;j++)//记住多次取余,否则会中间溢出 {z.a[i][j]=(z.a[i][j]+(x.a[i][k]*y.a[k][j])%10000)%10000;}}}return z;}void maxtri_mod()//快速幂的过程! {while(n!=0){if(n%2!=0){res=maxtri(res,ori);}ori=maxtri(ori,ori);n/=2;}printf("%d\n",res.a[1][2]);//输出结果 }int main(){while(scanf("%d",&n)&&(n!=-1)){init();maxtri_mod();}return 0;}

 
0 0
原创粉丝点击