Brute-force Algorithm

Any fool but Brute knows that the function “funny” will be called too many times. Brute wants to investigate the number of times the function will be called, but he is too lazy to do it.
Now your task is to calculate how many times the function “funny” will be called, for the given a, b and n. Because the answer may be too large, you should output the answer module by P.
For each test cases, there are four integers a, b, P and n in a single line.
You can assume that 1≤n≤1000000000, 1≤P≤1000000, 0≤a, b<1000000.
3 3 4 10 3 4 5 13 5 3 2 19 100
Case #1: 2 Case #2: 11 Case #3: 12
#include<cstdio>
#include<cmath>
#define ll __int64
ll a,b,p,n;
struct Matrix{
ll v[2][2];
};
Matrix A={0,1,1,1},B={1,0,0,1};
ll euler(ll x){
ll i,ans=x,t=(ll)sqrt(x*10.0);
for(i=2;i<=t;i++)if(x%i==0){
ans=ans/i*(i-1);
while(x%i==0)x/=i;
}
if(x>1)ans=ans/x*(x-1);
return ans;
}
ll quickpow(ll x,ll n){
ll ans=1;
while(n){
if(n&1)ans=ans*x%p;
n>>=1;
x=x*x%p;
}
return ans;
}
Matrix mul(Matrix m1,Matrix m2,ll M){
int i,j,k;
Matrix c;
for(i=0;i<2;i++)for(j=0;j<2;j++){
c.v[i][j]=0;
for(k=0;k<2;k++)c.v[i][j]+=(m1.v[i][k]*m2.v[k][j])%M;
c.v[i][j]%=M;
}
return c;
}
Matrix Mpow(int n,ll M){
Matrix x=A,c=B;
while(n>=1){
if(n&1)c=mul(c,x,M);
n>>=1;
x=mul(x,x,M);
}
return c;
}
int main(){
int T,ca=1,i;
scanf("%d",&T);
while(T--){
scanf("%I64d%I64d%I64d%I64d",&a,&b,&p,&n);
printf("Case #%d: ",ca++);
if(n==1){printf("%I64d\n",a%p);continue;}
if(n==2){printf("%I64d\n",b%p);continue;}
if(n==3){printf("%I64d\n",((a%p)*(b%p))%p);continue;}
ll phi=euler(p),f1=0,f2=1,f3,aa,bb;bool j=0;
for(i=4;i<=n;i++){
f3=f1+f2;
if(f3>=phi){f3%=phi;j=1;break;}
f1=f2,f2=f3;
}
if(j){
Matrix res=Mpow(n-3,phi);
f1=res.v[1][0],f2=res.v[1][1],f3=f1+f2;
aa=f2%phi+phi,bb=f3%phi+phi;
}
else {aa=f3,bb=f1+f2;}
printf("%I64d\n",(quickpow(a,aa)*quickpow(b,bb))%p);
}
return 0;
}
419



被折叠的 条评论
为什么被折叠?



