HDU 1452 Happy 2004 快乐2004 :http://acm.hdu.edu.cn/showproblem.php?pid=1452
题面:
1 10000 0
6 10
题目大意:
求2004^x所有因子的和并对29求模之后的结果。
题目分析:
先对2004进行素因子分解,可以得到2004=2^2*3*167,则2004^x=2^(2x)*3^x*167^x; //素因子分解
由算数基本定理:Φ(n)为n的所有因子之和,则有:
由题意,可计算得:
根据上述公式,用快速幂求解即可;
其中用到的公式和定理如下:
(a/b)mod m=(b^-1*a)mod m // b^-1指的是b的逆元,要用扩展欧几里得求解,t徒手求解过程如下:
332*x+29*y=1
332=11*29+13
29=2*13+3
13=4*3+1
3=3*1
即gcd(332,29)=1
1=13-4*3
=13-4*(29-2*13)
=-4*29+9*13
=-4*29+9*(332-11*29)
=9*332-103*29
则x=9;
(a+b)mod m=(a mod m+b mod m)mod m
(a^b)mod m=(a mod m)^b mod m
(a*b)mod m=((a mod m)*(b mod m))mod m
附快速幂代码:
long long quick_mod(long long a,long long b,long long M) { long long ans=1; while(b) { if(b&1) { ans=(ans*a)%M; b--; } b/=2; a=a*a%M; } return ans; }
代码实现:
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <time.h> using namespace std; typedef long long ll; const int INF = 0x3f3f3f3f; const double eps = 1e-4; const int M=29; long long quick_mod(long long a,long long b) { long long ans=1; while(b) { if(b&1) { ans=(ans*a)%M; b--; } b/=2; a=a*a%M; } return ans; } int main() { int x; while(scanf("%d",&x)!=EOF) { if(x==0) break; int sum; int a=(quick_mod(2,2*x+1)-1)%29; int b=(quick_mod(3,x+1)-1)%29; int c=(quick_mod(22,x+1)-1)%29; sum=(9*a*b*c)%29; printf("%d\n",sum); } return 0; }