Description
A^B % P is a very interesting problem. Here a more bigger problem needs you to solve.
((((A^B[0])^B[1])^…)^B[n-1])%P
In which B[i]=B[i-1]^2-1( i > 0 ), P=1e9+7
Input
The input consists of several test cases.
The first line of the input contains a single integer T (0 < T ≤ 20), the number of test cases.
Then Followed by T lines, each line gives a test case which contains three integers A, n and B0.
0<A<2^31 0<n<=10000 1<B[0]<2^31
Output
For each test case, output an integer representing the result of (((A^B[0])^B[1])^…)^B[n-1]%P
Sample Input
2
3 1 2
2 2 2
Sample Output
9
64
解题思路:
我们知道求解A^B%P,我们可以使用快速幂指数的运算公式 A^B^C=A^(B*C) 费马小定理 如果P为素数,A^(P-1)%P=1;于是运用费马小定理我们就能发现指数B0*B1*B2*…*Bn可以变小为(B0*B1*B2*…*Bn)%(P-1)。最后我们得出解题步骤 1、用循环求出B1,B2,…,Bn 2、对他们的乘积%(P-1) 3、快速幂求答案最后程序复杂度为O(N+log(P))
#include<iostream>
using namespace std;
const int P = 1000000007;
long long fastPow(long long x,long long y)
{
long long ans = 1;
while(y)
{
if(y&1)
ans *= x;
ans %= P;
y >>= 1;
x = x*x%P;
}
return ans;
}
int main()
{
int T;
cin>>T;
while(T--)
{
int A,n,B0;
cin>>A>>n>>B0;
long long BI = B0;
long long pow = B0;
for(int i=1;i<=n-1;++i)
{
BI = (BI*BI-1)%(P-1);
pow = pow*BI%(P-1);
}
cout<<fastPow(A,pow)<<endl;
}
return 0;
}
最后欢迎大家访问我的个人网站: 1024s