1. 程式人生 > >POJ 1995 Raising Modulo Numbers(快速冪取模)

POJ 1995 Raising Modulo Numbers(快速冪取模)

POJ1995

題目大意

有N個人,每個人給出兩個數字a,b,求∑(Ai\^Bi) mod M。

Input

3
16
4
2 3
3 4
4 5
5 6
36123
1
2374859 3029382
17
1
3 18132

Output

2
13195
13

程式碼

#include <iostream>
#include <cstdio>
typedef long long LL;

LL quick(LL a,LL b,int c)
{
    LL ans=1;   //記錄結果
    a=a%c;   //預處理,使得a處於c的資料範圍之下
while(b!=0) { if(b&1) ans=(ans*a)%c; //如果b的二進位制位不是0,那麼我們的結果是要參與運算的 b>>=1; //二進位制的移位操作,相當於每次除以2,用二進位制看,就是我們不斷的遍歷b的二進位制位 a=(a*a)%c; //不斷的加倍 } return ans; } int main() { int t; int M,N,i; LL e,f; scanf("%d",&t); while(t--) { LL sum=0
; scanf("%d%d",&M,&N); for(i=0;i<N;i++) { scanf("%lld%lld",&e,&f); sum+=quick(e,f,M); } sum%=M; printf("%lld\n",sum); } return 0; }