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
不难推出的是1+sn=fib(n+2);
所以求的是gcd(fib(n+2),fib(m+2));
然后又有gcd(fib(n),fib(m))=fib(gcd(n,m));
所以最后求的就是fib(gcd(n+2,m+2));
然后fib的第n项用矩阵快速幂求一下就可以了。
#include <bits/stdc++.h>
using namespace std;
const int MAXN=1e5+7;
const int inf=1e9;
int n,m,k,mod;
struct matrix
{
long long a[2][2];
matrix operator * (const matrix &y)const
{
matrix ans;
ans.a[0][0]=((a[0][0]*y.a[0][0])%mod+(a[0][1]*y.a[1][0])%mod)%mod;
ans.a[0][1]=((a[0][0]*y.a[0][1])%mod+(a[0][1]*y.a[1][1])%mod)%mod;
ans.a[1][0]=((a[1][0]*y.a[0][0])%mod+(a[1][1]*y.a[1][0])%mod)%mod;
ans.a[1][1]=((a[1][0]*y.a[0][1])%mod+(a[1][1]*y.a[1][1])%mod)%mod;
return ans;
}
};
long long get_f(int n)
{
if(n==1||n==2)return 1;
n-=2;
matrix result={{1,0,0,1}};
matrix base={{0,1,1,1}};
while(n)
{
if(n&1)result=result*base;
base=base*base;
n>>=1;
}
return (result.a[0][1]+result.a[1][1])%mod;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&mod);
printf("%lld\n",get_f(__gcd(n+2,m+2)));
}
return 0;
}