XDOJ1265 - A^B % P

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值