您的位置:首页 > 大数据 > 人工智能

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 F
mod 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: