poj 3070 Fibonacci
来源:互联网 发布:网络人肉违法 编辑:程序博客网 时间:2024/05/01 02:45
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:
.
题意:
求第n个fibonacci数后四位值
解析:
根据题目给定的方法,可以肯定会用到求快速幂的方法。快速幂就是当n为偶数时,a^n=a^(n/2)*a^(n/2),而后递归求;当n为奇数时,a^n=a^((n-1)/2)*a^((n-1)/2)*a,而后往下递归a^((n-1)/2),此处不同的就是矩阵的乘法,可以通过结构来定义
#include<stdio.h>struct matrix{int v[2][2];};//为了递归的时候返回值方便,所以把矩阵定义在结构里面matrix num;matrix multi(matrix a,matrix b)//矩阵a乘矩阵b{matrix m;m.v[0][0] =m.v[0][1] = m.v[1][0]= m.v[1][1] = 0;int i,j,k;for(i = 0 ; i < 2; i ++)for(j = 0 ; j < 2; j ++)for(k = 0; k < 2; k ++)m.v[i][j] = (m.v[i][j] + a.v[i][k] * b.v[k][j] ) %10000;//此处不可以换成m.v[i][j] += (a.v[i][k] * b.v[k][j] ) %10000;,因为这是会叠加超过10000的,//例如m.v[i][j]等于9000时,a.v[i][k] * b.v[k][j] 等于3000,加一起就超过10000了return m; }matrix fx(int n)//num的n次方{matrix t,a;if(n == 1)return num;if(n%2==0){a = fx(n/2);t = multi(a,a);}else{a = fx((n-1)/2);t = multi( a,a );t = multi(t,num);}return t;}int main(){int n;while(scanf("%d",&n) != EOF && n != -1) {int i;num.v[0][0] = num.v[0][1] = num.v[1][0]= 1;num.v[1][1] = 0;if(n == 0)printf("0\n");elseprintf("%d\n",fx(n-1).v[0][0]);}return 0;}
- POJ 3070 Fibonacci
- POJ 3070 Fibonacci
- poj 3070 Fibonacci
- poj 3070 Fibonacci
- poj 3070 Fibonacci
- poj 3070 Fibonacci
- POJ 3070 Fibonacci
- poj 3070:Fibonacci
- POJ FIBONACCI (3070)
- POJ 3070 Fibonacci
- POJ 3070 Fibonacci (矩阵)
- POJ 3070 Fibonacci
- POJ 3070 Fibonacci
- poj-3070-Fibonacci
- poj 3070 Fibonacci
- POJ 3070 Fibonacci
- poj 3070 Fibonacci
- poj 3070 Fibonacci
- KMP算法详解
- KMP算法实现
- red5+ffmpeg
- Redis源码分析之事务
- OCM 考试说明
- poj 3070 Fibonacci
- zoj1665-Transport Goods
- 由于无法安装KB2670838导致无法安装IE10的原因及解决方法
- 课程设计--PCB板的设计
- 3好书1
- [Oracle] 谈谈Lock和Latch
- 客户端、pbo、fbo、texture之间数据传输特点
- 关于virtualbox内的虚拟机克隆问题
- ubuntu下设置共享目录