题目链接:http://poj.org/problem?id=1995
标准的快速幂的题目,唯一需要注意的就是:结果要用long long int。开始不知道,第二个样例怎么也过不了,后来看了书上的代码才知道……
其实应该想到要用LL的,这种错误应该自己查出来,题目中虽然没有说 Ai, Bi 的范围,但是保险起见,应该用LL啊。惭愧……
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cctype> 6 #include <stack> 7 #include <queue> 8 #include <cmath> 9 #include <algorithm> 10 #define lson l, m, rt<<1 11 #define rson m+1, r, rt<<1|1 12 using namespace std; 13 typedef long long int LL; 14 const int MAXN = 0x3f3f3f3f; 15 const int MIN = -0x3f3f3f3f; 16 17 int m; 18 LL power(LL a, LL k){ 19 LL ans = 1; 20 while (k){ 21 if (k&1){ 22 ans = (ans * a) % m; k--; 23 } 24 k >>= 1; a = (a*a)%m; 25 } 26 return ans; 27 } 28 int main(void){ 29 #ifndef ONLINE_JUDGE 30 freopen("1995.in", "r", stdin); 31 #endif 32 int t; scanf("%d", &t); 33 int a, b, h; LL ans; 34 while (t--){ 35 scanf("%d%d", &m, &h); 36 ans = 0; 37 while (h--){ 38 scanf("%d%d", &a, &b); 39 ans += (power(a, b)%m); 40 } 41 ans %= m; 42 printf("%lld\n", ans); 43 } 44 45 return 0; 46 }
有点儿乱……其实代码挺好写的