题目链接:Sicily2501
题目概述:S = n^1 + n^2 + n^3 +...... + n^k,已知n、k,求S除以9901的余数。
根据费马小定理:假如p是质数,且(a,p)=1(即a,p互质),那么 a^(p-1) ≡1(mod p)。即:假如p是质数,且a,p互质,那么a的(p-1)次方除以p的余数恒等于1。
可知9901是质数,所以n^9900%9901=1,
即存在:( n^ (9900+m)) % 9901 = ( n^9900 * n^m ) % 9901 = ( n^9900 % 9901 * n^m ) % 9901 = n^m % 9901
(例:n^9901 % 9901 = n、n^9902 % 9901 = n^2)以此类推,以9900为一个周期
故原问题变为:
n^1 + n^2 + n^3 +...... + n^k mod 9901 =((n^1 + ... + n^9900)(k/9900)+(n^1 + ... + n^(k% 9900)) ) mod9901
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; int main() { int i,a[9905]; int n,k,m; while(~scanf("%d%d",&n,&k)) { a[0] = 0, a[1] = m = n%9901; for(i = 2; i <= 9900; i ++) { m = m*n%9901; a[i] = (a[i-1] + m)%9901; } printf("%d\n",(k/9900*a[9900] + a[k%9900])%9901); } return 0; }
原文:http://blog.csdn.net/jzmzy/article/details/19763703