Elegant fibonacci numbers again
2014-03-11 20:47
399 查看
Problem Description
Fibonacci numbers are nice simple integers. All of you are familiar with it, aren’t you?The Fibonacci sequence <F
> are defined by the recurrence:
F[0]=0;
F[1]=1;
F
=F[n-1]+F[n-2], for n>1
You know that the value of F
increases rapidly when the n becomes larger. So for each test case,output the value F
mod m will be ok.
Input
The first line of the input is a positive integer.It is the number of the test cases followed. Each test case contains two integers n (0<=n<2^32) and m (0<m<10000). There may be one or several spaces between the two integers.
Output
The output of the program should consist of one line of output for each test case.The output of each test case only contains one integer which equals to the value Fmod m. No any redundant spaces are needed.
Sample Input
2 1 1000 2 100
Sample Output
1 1
// 关键字: 斐波拉契数列的矩阵求法
//标程:
#include<stdio.h> struct ss { int a[2][2]; }; ss fun(ss x,ss y,__int64 m) { ss ret; ret.a[0][0]=(x.a[0][0]*y.a[0][0]%m+x.a[0][1]*y.a[1][0]%m)%m; ret.a[0][1]=(x.a[0][0]*y.a[0][1]%m+x.a[0][1]*y.a[1][1]%m)%m; ret.a[1][0]=(x.a[1][0]*y.a[0][0]%m+x.a[1][1]*y.a[1][0]%m)%m; ret.a[1][1]=(x.a[1][0]*y.a[0][1]%m+x.a[1][1]*y.a[1][1]%m)%m; return ret; } ss f(ss ans,__int64 n,__int64 m) { ss ret,temp; if(n==0) { ret.a[0][0]=1, ret.a[0][1]=0; ret.a[1][0]=0, ret.a[1][1]=1; return ret; } if(n==1) return ans; temp=f(ans,n/2,m); ret=fun(temp,temp,m); if(n%2==1) ret=fun(ret,ans,m); return ret; } int main() { //freopen("a.txt","r",stdin); __int64 n,m; int t,i; scanf("%d",&t); while(t--) { scanf("%I64d%I64d",&n,&m); if(n==0) { printf("0\n"); continue;} ss ans; ans.a[0][0]=1, ans.a[0][1]=1; ans.a[1][0]=1, ans.a[1][1]=0; ss s=f(ans,n-1,m); printf("%d\n",s.a[0][0]); } return 0; }
相关文章推荐
- Elegant fibonacci numbers again
- hdu 1848 Fibonacci again and again 博弈论,求出SG函数,,什么问题都没有了
- 哈理工邀请赛 F.Fibonacci Again (矩阵快速幂)
- 11582 - Colossal Fibonacci Numbers!
- HDU 1848 Fibonacci again and again(博弈sg函数)
- HDU_1848 Fibonacci again and again(SG函数应用)
- HDU 1848 Fibonacci again and again
- HDU1848 Fibonacci again and again
- Colossal Fibonacci Numbers! UVA 11582 寻找循环节
- HDU 1848 Fibonacci again and again(每次只能取fibonacci数的NIM)
- UVA 11582 Colossal Fibonacci Numbers!(数论)
- HDU 1848 Fibonacci again and again(SG函数)
- hdu1848 Fibonacci again and again(SG游戏功能)
- HDU 1848[Fibonacci again and again] 题解
- CodeForces 446C DZY Loves Fibonacci Numbers(线段树+数论)
- hdu 1848 Fibonacci again and again
- HDOJ&nbsp;&nbsp;&nbsp;1021&nbsp;&nbsp;&nbsp;&nbsp;Fibonacci&nbsp;Again
- [ACM] hdu 1848 Fibonacci again and again(Nim博弈 SG函数)
- HDU 1848 Fibonacci again and again
- Sum All Odd Fibonacci Numbers