华华教月月做数学(快速幂)

华华教月月做数学(快速幂)

链接:https://ac.nowcoder.com/acm/problem/23046
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld

题目描述

找到了心仪的小姐姐月月后,华华很高兴的和她聊着天。然而月月的作业很多,不能继续陪华华聊天了。华华为了尽快和月月继续聊天,就提出帮她做一部分作业。
月月的其中一项作业是:给定正整数A、B、P,求ABmod  P的值。华华觉得这实在是毫无意义,所以决定写一个程序来做。但是华华并不会写程序,所以这个任务就交给你了。
因为月月的作业很多,所以有T组询问。

输入描述:

第一行一个正整数T表示测试数据组数。
接下来T行,每行三个正整数A、B、P,含义如上文。

输出描述:

输出T行,每行一个非负整数表示答案。

示例1

输入

2
2 5 10
57284938291657 827493857294857 384729583748273

输出

2
18924650048745

备注:

 1≤T≤103,1≤A, B, P≤1018

 

快速幂模板题

但是P的值很大,可以达到1018,所以,我们不能直接打快速幂,要用__int128储存中间计算结果,避免爆LL

 

#include <bits/stdc++.h>
typedef long long LL;
#define pb push_back
#define mst(a) memset(a,0,sizeof(a))
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
const int mod = 1e9+7;
const int maxn = 1e5+10;
using namespace std;

__int128 fpow(__int128 a, __int128 b,__int128 mo)
{
    if (a == 0) return 0;
    __int128 ans = 1;
    for (; b; b >>= 1, a = (a % mo * a% mo) % mo)
        if (b & 1) ans = (ans % mo * a % mo) % mo;
    return ans;
}

int main()
{
    #ifdef DEBUG
    freopen("sample.txt","r",stdin); //freopen("data.out", "w", stdout);
    #endif
    
    int T;
    scanf("%d",&T);
    while(T--)
    {
        LL a,b,p;
        scanf("%lld %lld %lld",&a,&b,&p);
        printf("%lld\n",(LL)fpow((__int128)a,(__int128)b,(__int128)p));
    }
    
    return 0;
}

 

 

Python做法:

T = int(input())
for _ in range(T):
    a,b,c = map(int,input().split())
    print(pow(a,b,c))

 

 

 

 

 

-

posted @ 2020-07-01 21:02  jiamian22  阅读(241)  评论(0)    收藏  举报