矩阵乘法快速幂 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; }
相关文章推荐
- Java学习之LinkedHashMap
- [已解决]Android Studio 2.1.1 运行时候显示 No changes To Deploy 但是其实已经更新了的,闪电运行的问题
- spring和springMVC父子容器的原理
- leetcode 230. Kth Smallest Element in a BST
- 计算原理课程笔记(一)
- android常用的函数、判断、正则
- UI(base)-2
- Android Studio代码调试技巧篇
- leecode_220 Contains Duplicate III
- App Transport Security
- ACdream 1188 switch教学
- 简单理解Socket
- Ubuntu下安装RabbbitVCS(图形化svn管理工具)- Ubuntu也有TortoiseSVN
- swift 字符串创建类
- DKIM对发送邮件的好处及使用方法
- FZU-2105 Digits Count (两种标记成段更新)
- VS2005 Debug版,dll /MTd,exe /MDd 跨dll使用CString的链接错误
- Java基础资料
- 电话信用标记数据的爬虫
- iOS设计模式 - (2)UML类间关系精解