0
点赞
收藏
分享

微信扫一扫

POJ1995 Raising Modulo Numbers【整数快速幂】

云竹文斋 2022-07-27 阅读 24


题目链接:

​​http://poj.org/problem?id=1995​​


题目大意:

N个人在一起玩游戏,每个人默写两个数字Ai、Bi,在同一个时间公开给其他玩家看。游戏的目的是

为了看谁能够在最快的时间求出所有的Ai^Bi的和对M取模的值。那么问题来了:你能够快速算出

(A1B1+A2B2+ ... +AHBH)mod M 的值吗?


思路:

用二分整数快速幂算法计算出每一个Ai^Bi,然后依次相加取模。


AC代码:


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define LL __int64
using namespace std;

LL QuickMod(LL a,LL b,LL m)
{
LL ans = 1;
while(b)
{
if(b&1)
{
ans = ans*a%m;
b--;
}
a = a*a%m;
b >>= 1;
}
return ans;
}

int main()
{
int N,M,T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&M,&N);
LL a,b,ans = 0;
for(int i = 1; i <= N; ++i)
{
scanf("%I64d%I64d",&a,&b);
ans = (ans + QuickMod(a,b,M)) % M;
}
printf("%I64d\n",ans);
}

return 0;
}



举报

相关推荐

0 条评论