题解【CJOJ1236】【复赛】指数序列求和

Description

求1^b+2^b+…+a^b的和除以10000的余数。

Input

第一行包含一个正整数N,表示有N组测试数据
接下来N行每行包含两个正整数a和b

Output

共N行,每行一个对应的答案

Sample Input


2 3

Sample Output

9

Hint

数据范围:

对于30%数据n≤10,a,b≤1000

对于100%数据n≤100,a,b≤1000000000

Source

位运算,二分,快速幂

Solution

由标签和数据范围可知,这题是个枚举模数的题。(有二分吗)

我们分析之后就会发现a^b和(a+mod)^b对答案的影响是一样的,证明是显然的。

所以说我们对于任意i^b都可以写成(i%mod)^b,那么只需要把mod打表打下来就可以一次计算完了,打表的时候用倍增快速幂即可。

——摘自这里

知道这个后,这就是一个快速幂取模的水题啦!

Code

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 const int mod = 10000;
 6 
 7 inline int read()
 8 {
 9     int f=1,x=0;
10     char c=getchar();
11 
12     while(c<'0' || c>'9')
13     {
14         if(c=='-')f=-1;
15         c=getchar();
16     }
17 
18     while(c>='0' && c<='9')
19     {
20         x=x*10+c-'0';
21         c=getchar();
22     }
23 
24     return f*x;
25 }
26 
27 inline int Qpow(int a,int b)
28 {
29     int r=1;
30 
31     while(b)
32     {
33         if(b&1)
34         {
35             r=r*a%mod;
36         }
37 
38         a=a*a%mod;
39 
40         b=b>>1;
41     }
42 
43     return r%mod;
44 }
45 
46 int t,a,b,ans,sum;
47 
48 int main()
49 {
50     t=read();
51 
52     while(t--)
53     {
54         a=read(),b=read();
55 
56         ans=0,sum=a/mod;
57         
58         a=a%mod;
59 
60         for(register int i=1; i<=mod; i++)
61         {
62             if(i<=a)
63             {
64                 ans=(ans+(sum+1)*Qpow(i,b))%mod;
65             }
66             else 
67             {
68                 ans=(ans+sum*Qpow(i,b))%mod;
69             }
70         }
71         
72         printf("%d
",ans);
73     }
74     
75     return 0;
76 }
原文地址:https://www.cnblogs.com/xsl19/p/10492060.html