您的位置:首页 > 产品设计 > UI/UE

HDU 5667 Sequence(数论+矩阵快速幂)

2016-05-03 10:30 417 查看
Description

已知数列f(n)的递推公式如下:



现给出n,a,b,c,p,求f(n)%p

Input

第一行为一整数T表示用例组数,每组用例占一行包括五个整数n,a,b,c,p

(1≤T≤10,1≤n≤10^18,1≤a,b,c≤10^9,p是素数且p≤10^9+7)

Output

对于每组用例,输出f(n)%p

Sample Input

1

5 3 3 3 233

Sample Output

190

Solution

费马小定理+矩阵快速幂



Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 11
typedef long long ll;
struct Mat
{
ll mat[maxn][maxn];//矩阵
int row,col;//矩阵行列数
};
Mat mod_mul(Mat a,Mat b,int p)//矩阵乘法
{
Mat ans;
ans.row=a.row;
ans.col=b.col;
memset(ans.mat,0,sizeof(ans.mat));
for(int i=0;i<ans.row;i++)
for(int k=0;k<a.col;k++)
if(a.mat[i][k])
for(int j=0;j<ans.col;j++)
{
ans.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
ans.mat[i][j]%=p;
}
return ans;
}
Mat mod_pow(Mat a,ll k,ll p)//矩阵快速幂
{
//printf("k=%I64d p=%I64d\n",k,p);
Mat ans;
ans.row=a.row;
ans.col=a.col;
for(int i=0;i<a.row;i++)
for(int j=0;j<a.col;j++)
ans.mat[i][j]=(i==j);
while(k)
{
if(k&1)ans=mod_mul(ans,a,p);
a=mod_mul(a,a,p);
k>>=1;
}
return ans;
}
ll Mod_pow(ll a,ll b,ll p)
{
a%=p;
ll ans=1ll;
while(b)
{
if(b&1)ans=ans*a%p;
a=a*a%p;
b>>=1;
}
return ans;
}
int main()
{
int T;
ll n,a,b,c,p;
scanf("%d",&T);
while(T--)
{
scanf("%I64d%I64d%I64d%I64d%I64d",&n,&a,&b,&c,&p);
Mat A,B;
A.row=A.col=3;
A.mat[0][0]=c,A.mat[0][1]=1,A.mat[0][2]=b;
A.mat[1][0]=1,A.mat[1][1]=0,A.mat[1][2]=0;
A.mat[2][0]=0,A.mat[2][1]=0,A.mat[2][2]=1;
if(n==1)printf("1\n");
else if(n==2)printf("%I64d\n",Mod_pow(a,b,p));
else
{
B=mod_pow(A,(n-2),(p-1));
ll temp=B.mat[0][0]*b+B.mat[0][2];
ll ans=Mod_pow(a,temp,p);
printf("%I64d\n",ans);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: