1202: GCD
Time Limit: 1 Sec Memory Limit: 1280 MBSubmit: 184 Solved: 26
[ Submit][ Status][ Web Board]
Description
Input
The first line is an positive integer T . (1<=T<= 10^3) indicates the number of test cases. In the next T lines, there are three positive integer n, m, p (1<= n,m,p<=10^9) at each line.
Output
Sample Input
1
1 2 3
Sample Output
1
如题所求,其实很简单,只要知道菲波纳契数列前n项和等于第n+2项减1就能轻松AC
先科普一下:
http://blog.sina.com.cn/s/blog_a6f9a3b60102vt3e.html
http://blog.csdn.net/it_beecoder/article/details/52913291
http://blog.csdn.net/xuzengqiang/article/details/7645020
http://blog.csdn.net/qq_15571091/article/details/48528041
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <stack>
using namespace std;
typedef long long ll;
#define PI 3.1415926535897932
#define E 2.718281828459045
#define INF 0xffffffff//0x3f3f3f3f
#define MAX 10
#define CLR(arr,val) memset(arr,val,sizeof(arr))
#define Bit(n) 1<<n
//const int M=1005;
ll n,m,p;
struct node
{
int v,w;
node(int vv,int ww)
{
v=vv;
w=ww;
}
};
class Matrix{
public:
Matrix(int r,int c):row(r),col(c){}
void Init()
{ CLR(map,0);
map[0][0]=map[0][1]=map[1][0]=1;
}
void Unit() //初始化为单位矩阵
{ CLR(map,0);
for(int i=0;i<row;i++)
map[i][i]=1;
}
ll Result() const{return map[0][1]%p;}
friend Matrix operator*(const Matrix& ,const Matrix&);
ll Pow(ll);
private:
ll map[MAX][MAX];
int row,col;
};
Matrix operator*(const Matrix& M1,const Matrix& M2) //矩阵相乘模板
{ Matrix M(M1.row,M2.col); //相乘之后矩阵的行和列会变化
for(int i=0;i<M1.row;i++)
for(int j=0;j<M2.col;j++)
{ M.map[i][j]=0;
for(int k=0;k<M1.col;k++)
M.map[i][j]=(M.map[i][j]+((M1.map[i][k]%p)*(M2.map[k][j]%p))%p)%p;
}
return M;
}
Matrix M(2,2);
ll Matrix::Pow(ll n) //矩阵快速幂
{ Matrix temp(2,2);
temp.Init();
for(ll i=0;Bit(i)<=n;i++) //利用二进制的思想求解
{ if(Bit(i)&n) M=M*temp;
temp=temp*temp;
}
return M.Result();
}
ll gcd(ll a,ll b){
if(b==0)return a;
else return gcd(b,a%b);
}
int main()
{
int i,j,k,t;
int l,g;
int ans;
//getpri();
scanf("%d",&t);
while(t--)
{
M.Unit();
int num;
cin>>n>>m>>p;
//printf("%lld\n",);
//printf()
// printf("%d\n",gcd(4,2));
cout<<M.Pow(gcd(n+2,m+2))%p<<endl;
}
return 0;
}