bit 1047 Fibonacci Numbers
来源:互联网 发布:电机控制算法工程师 编辑:程序博客网 时间:2024/06/04 00:56
Fibonacci Numbers
ProblemDescription
The Fibonacci sequence is the sequence of numbers such that everyelement is equal to the sum of the two previous elements, except for the firsttwo elements f[0] and f[1] which are respectively zero and one.
What is the numerical value of the f[n]? Because the number may be very huge,you just need to output the f[n] mod p.
Input
There are multiply test cases. Each test case, there is one linecontains two integers n and p (0 <= n <= 10^9, 1 <= p <= 10^9).
Output
For each test case, output an integer, denotes the result of f[n]mod p.
Sample Input
0 9997
1 9997
2 9997
Sample Output
0
1
1
构造矩阵 进行快速幂
f[n] 1 1 f[n-1]
= *
f[n-1] 1 0 f[n-2]
#include <stdio.h>long long int base[2][2]= {{1,1},{1,0}};long long int res[2][2];void q_p(long long N,long long mod){long long a = 1;long long tmp[2][2];for(int i = 0;i <2;++i) for(int j = 0;j <2;++j)base[i][j] = 1; base[1][1]= 0;res[0][0] = 1;res[0][1] = 0;res[1][0] = 0;res[1][1] = 1;while(a<=N){if(a&N){for(int i = 0;i<2;++i)for(int j = 0;j<2;++j){tmp[i][j] = 0;for(int k = 0;k < 2;++k){tmp[i][j] += res[i][k] * base[k][j]; tmp[i][j] %= mod;}}for(int i = 0;i<2;++i)for(int j = 0;j<2;++j){res[i][j]=tmp[i][j];}}for(int i = 0;i<2;++i) for(int j = 0;j<2;++j) { tmp[i][j] = 0; for(int k = 0;k < 2;++k){ tmp[i][j] += base[i][k] * base[k][j]; tmp[i][j] %= mod; } } for(int i = 0;i<2;++i) for(int j = 0;j<2;++j){ base[i][j]=tmp[i][j]; }a <<=1;}return;}int main(int argc, char const *argv[]){long long int n,mod;while(~scanf("%lld%lld",&n,&mod)){q_p(n,mod);printf("%lld\n",res[1][0]);}return 0;}
- bit 1047 Fibonacci Numbers
- BITACM 1047 Fibonacci Numbers
- Fibonacci numbers
- Fibonacci Numbers
- Fibonacci Numbers
- Fibonacci Numbers
- Fibonacci numbers
- 2013寒假练习 1047 Fibonacci Numbers
- HDU 3117 Fibonacci Numbers
- hdu 3117 Fibonacci Numbers
- hdu3117 Fibonacci Numbers
- zoj 1828 Fibonacci Numbers
- java fibonacci Numbers
- UVa10579 Fibonacci Numbers
- zoj 1828 Fibonacci Numbers
- HDOJ 3117 - Fibonacci Numbers
- hdu 3117 Fibonacci Numbers
- Hdu 3117 Fibonacci Numbers
- 图的遍历
- SSH原理与运用(一):远程登录
- iphone——视图layout
- gwt 环境搭建
- Struts2校验框架的错误显示位置问题
- bit 1047 Fibonacci Numbers
- Linux下获取本地IP地址--------getifaddrs
- SSH原理与运用(二):远程操作与端口转发
- Android深入浅出之binder机制
- C++中 public protected private 访问权限
- sphinx4 声学模型自适应
- C++各种没优化朴素贪食蛇100行代码
- 链表动态加载范例
- 检查数据库中某记录是否重复