Holion August will eat every thing he has found.
Now there are many foods,but he does not want to eat all of them at once,so he find a sequence.
fn=⎧⎩⎨⎪⎪1,ab,abfcn−1fn−2,n=1n=2otherwisefn={1,n=1ab,n=2abfn−1cfn−2,otherwise
He gives you 5 numbers n,a,b,c,p,and he will eat fnfn foods.But there are only p foods,so you should tell him fnfn mod p.
Input
The first line has a number,T,means testcase.
Each testcase has 5 numbers,including n,a,b,c,p in a line.
1≤T≤10,1≤n≤1018,1≤a,b,c≤109 1≤T≤10,1≤n≤1018,1≤a,b,c≤109,pp is a prime number,and p≤109+7p≤109+7.
Output
Output one number for each case,which is fnfn mod p.
Sample Input
1 5 3 3 3 233
Sample Output
190
详细思路:
费马小定理对幂次优化:求kn的过程中对p-1取余,求a^kn对p取余
需要注意:如果a是p的倍数即a%p==0的话,a^kn%p为0
一开始错误原因:
1.前边三个if判断不成立直接continue造成了t--没有执行
2.对于n==2的情况,要先判断a%p是否为0,再求解
代码:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static long n,a,b,c,p;
static final int max=3;
public static long[][] multi(long aa[][],long bb[][]){
long res[][]=new long[max][max];
for(int i=0;i<max;i++)
Arrays.fill(res[i], 0);
for(int i=0;i<max;i++)
for(int j=0;j<max;j++)
for(int k=0;k<max;k++)
res[i][j]=(res[i][j]+aa[i][k]*bb[k][j]%(p-1))%(p-1);
return res;
}
public static long[][] quick_pow1(long aa[][],long t){
long res[][]=new long[max][max];
for(int i=0;i<max;i++)
for(int j=0;j<max;j++)
if(i==j) res[i][j]=1;
else res[i][j]=0;
while(t>0){
if((t&1)==1) res=multi(res,aa);
t/=2;
aa=multi(aa,aa);
}
return res;
}
public static long quick_pow2(long aa,long bb){
long res=1;
while(bb!=0){
if((bb&1)==1) res=res*aa%p;
bb/=2;
aa=aa*aa%p;
}
return res%p;
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
while(t>0){
n=scan.nextLong();
a=scan.nextLong();
b=scan.nextLong();
c=scan.nextLong();
p=scan.nextLong();
if(n==1){
System.out.println("1");
}
else if(a%p==0){
System.out.println("0");
}
else if(n==2){
long s=quick_pow2(a,b);
System.out.println(s);
}
else{
long init[][]=new long[max][max];
for(int i=0;i<max;i++)
Arrays.fill(init[i], 0);
init[0][0]=c;
init[0][1]=init[0][2]=init[1][0]=init[2][2]=1;
long res[][]=new long[max][max];
res=quick_pow1(init,n-2);
long c[][]=new long[max][max];
for(int i=0;i<max;i++)
Arrays.fill(c[i], 0);
c[0][0]=c[2][0]=b;
long kn=(res[0][0]*c[0][0]%(p-1)+res[0][1]*c[1][0]%(p-1)+res[0][2]*c[2][0]%(p-1))%(p-1);
System.out.println(quick_pow2(a,kn));
}
t--;
}
}
}