您的位置:首页 > 其它

矩阵乘法快速幂 codevs 1250 Fibonacci数列

2016-06-02 11:32 344 查看

codevs 1250 Fibonacci数列

时间限制: 1 s

空间限制: 128000 KB

题目等级 : 钻石 Diamond

题目描述 Description

定义:f0=f1=1, fn=fn-1+fn-2(n>=2)。{fi}称为Fibonacci数列。

输入n,求fn mod q。其中1<=q<=30000。

输入描述 Input Description

第一行一个数T(1<=T<=10000)。

以下T行,每行两个数,n,q(n<=109, 1<=q<=30000)

输出描述 Output Description

文件包含T行,每行对应一个答案。

样例输入 Sample Input

3

6 2

7 3

7 11

样例输出 Sample Output

1

0

10

数据范围及提示 Data Size & Hint

1<=T<=10000

n<=109, 1<=q<=30000

分类标签 Tags 点此展开

矩阵乘法 数论

#define N 3
#include<iostream>
using namespace std;
#include<cstdio>
#include<cstring>
struct Jz{
int cal,line;
int jz

;
};
int q;
int read()
{
char s;
int ans=0,ff=1;
s=getchar();
while(s<'0'||s>'9')
{
if(s=='-') ff=-1;
s=getchar();
}
while('0'<=s&&s<='9')
{
ans=ans*10+s-'0';
s=getchar();
}
return ans*ff;
}
Jz martax(Jz x,Jz y)
{
Jz ans;
ans.line=x.line;
ans.cal=y.cal;
for(int i=1;i<=ans.line;++i)
for(int j=1;j<=ans.cal;++j)
{
ans.jz[i][j]=0;
for(int k=1;k<=x.cal;++k)
ans.jz[i][j]=(ans.jz[i][j]+x.jz[i][k]*y.jz[k][j])%q;
}
return ans;
}
int Fast_martax(int n)
{
if(n==0||n==1) return 1;
n--;
Jz ans,a;
a.cal=a.line=2;
a.jz[1][1]=0;a.jz[1][2]=1;
a.jz[2][1]=1;a.jz[2][2]=1;
ans.line=2;ans.cal=1;
ans.jz[1][1]=1;ans.jz[2][1]=1;
while(n)
{
if(n&1)
{
ans=martax(a,ans);
}
n>>=1;
a=martax(a,a);
}
return ans.jz[2][1]%q;
}
int main()
{
int T,n;
T=read();
while(T--)
{
n=read();q=read();
printf("%d\n",Fast_martax(n));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: