poj 3070 Fibonacci 【矩阵快速幂】
来源:互联网 发布:电脑端扫描仪软件 编辑:程序博客网 时间:2024/06/04 00:51
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
#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;}
- POJ 3070 Fibonacci 矩阵快速幂
- poj - 3070 - Fibonacci(矩阵快速幂)
- 矩阵快速幂 Fibonacci 3070 poj
- POJ 3070 Fibonacci (矩阵快速幂)
- poj 3070 Fibonacci (矩阵快速幂)
- poj 3070 Fibonacci(矩阵快速幂)
- poj 3070 Fibonacci 矩阵快速幂
- POJ 3070 Fibonacci(矩阵快速幂)
- poj 3070 Fibonacci(矩阵快速幂)
- POJ-3070 Fibonacci 矩阵快速幂
- Fibonacci - POJ 3070 矩阵乘法快速幂
- poj 3070 Fibonacci(矩阵快速幂)
- poj 3070 Fibonacci 矩阵快速幂
- POJ 3070 Fibonacci(矩阵快速幂)
- POJ 3070 Fibonacci(矩阵快速幂)
- poj 3070 Fibonacci 矩阵快速幂
- poj 3070 Fibonacci 【矩阵快速幂】
- POJ 3070 Fibonacci.(矩阵快速幂)
- NYOJ 837 Wythoff Game(威佐夫博奕公式利用)
- UnityGUI 基础
- ZOJ.2421 Recaman's Sequence【暴力打表】 2015/09/24
- noip模拟小象涂色
- Android Studio安装SVN
- poj 3070 Fibonacci 【矩阵快速幂】
- 手游发展迅猛,渠道要搭建移动游戏生态圈才有出路
- python syntax points
- ShareSDK v3简化版 升级问题
- UVA539dfs搜一条无重复边的最长道路
- 工厂模式
- 9.24
- CGI,fastcgi和php-fpm
- ZOJ 2369 | SGU 217 | Acdream 1234 自适应辛普森积分