Peter's codebook A blog full of codes

POJ 1995 Raising Modulo Numbers

Fast pow!

傳送門

POJ1995

題目概述

求出

$$ \left( A_{1}^{B_{1}} + A_{2}^{B_{2}} + A_{3}^{B_{3}} + ... + A_{H}^{B_{H}} \right) \mod M $$

解題想法

應用餘的性質還有快速冪,就可以求出答案。

程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstdlib>
using namespace std;

typedef long long int UT;

UT fastpow(UT a, UT p, UT P) {
    UT t=a, res=1uLL;
    while(p>0uLL) {
        if(p&1uLL) {
            res = (res*t)%P;
        }
        t=(t*t)%P;
        p>>=1uLL;
    }
    return res%P;
}

int main(void) {
    UT a,p,K,M;
    int N, n;
    scanf("%d",&N);
    while(N--) {
        scanf("%lld",&M);
        scanf("%d",&n);
        UT ans=0;
        for(int i=0; i<n; ++i) {
            scanf("%lld%lld",&a,&K);
            ans += (fastpow(a,K,M)%M);                             
        }
        printf("%lld\n",ans%M);
    }
    
    return 0;
}
comments powered by Disqus