Problem A. Huge Numbers Google Kickstart Round G 2017

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yixin94/article/details/82053795

题意:calculate the remainder when A^(N!) is divided by P

A^n%P=(A*A*...*A)%P=(A%P)^n

A^(N!)%P=A^(1*2*...*N)%P=((A%P)^2)^(3*...*N)=((remainder of (A%P)^2)^3)^(4*...*N)。

由内向外维护一个remainder即可。

#include<iostream>
#include<stdio.h>
#include<cstdio>
#include<string>
#include<cmath>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<set>

using namespace std;

//kickstart 2017 Round G Problem A
int T;
const int maxn=100010;
long long N;
long long A;
long long P;
//long long factor[maxn];

long long pow_mod(long long a,long long b)
{
    long long s=1;
    long long t=1;
    while(b)
    {
        if(b&t)
        {
            s=(s*a)%P;
        }
        a=(a*a)%P;
        b=b>>1;
    }
    return s;
}
//long long check()
//{
//    long long ans2=A%P;
//    for(int i=2;i<=factor[N];i++)
//    {
//        ans2*=A;
//        ans2%=P;
//    }
//    //printf("%lld\n",ans2);
//    return ans2;
//}
int main()
{
    freopen("A-large.in","r",stdin);
    //freopen("input.txt","r",stdin);
    freopen("a2.txt","w",stdout);
//    factor[1]=1;
//    for(int i=2;i<=10;i++)
//    {
//        factor[i]=factor[i-1]*i;
//
//    }
//    for(int i=1;i<=10;i++)
//    {
//        cout<<factor[i]<<endl;
//
//    }
    //return 0;
    scanf("%d",&T);
    for(int ca=1;ca<=T;ca++)
    {
        scanf("%lld %lld %lld",&A,&N,&P);
        long long remain=A%P;
        long long ans=0;
        for(int i=1;i<=N;i++)
        {
            long long tmpans=pow_mod(remain,i);
            tmpans%=P;
            ans=tmpans;
//            if(i==1)
//            {
//                ans=tmpans;
//
//            }
//            else
//            {
//                ans=ans*tmpans;
//                ans%=P;
//            }
            remain=tmpans;

        }
        ans%=P;
        printf("Case #%d: %lld\n",ca,ans);
       // long long ans2=check();
        //printf("Case #%d: %lld\n",ca,check());
//        if(ans!=ans2)
//        {
//            cout<<A<<" "<<N<<" "<<P<<" "<<ans<<" "<<ans2<<endl;
//
//        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/yixin94/article/details/82053795