假设卡片上的标号为A1,A2,..An,跳蚤跳对应号的次数分别为X 1,X 2,...X n,跳M个单位的次数为X n+1,有以下方程成立:
A1*X1+A2*X2+......+An* Xn+M*X n+1 =1。
要使以上方程有解,(A1,A2,A3,..,M)=1
先对M 进行质因数分解。
设p=(A1,A2,....An,M)
然后排除p不等于1的情况即可。
对于任意一个小于等于m的数x,其倍数的出现次数为(m/x),对于n张纸牌,有(m/x)^n
然后枚举m的质因子b1,b2,..bt
根据容斥原理,先sum+=(m/b1)^n+(m/b2)^n+....+(m/bt)^n
然后减去重叠的部分sum-=(m/(b1*b2))^n+(m/(b1*b3))^n+....+(m/(b t-1*bt))^n
依次递推下去。
最后sum=m^n-sum即可。
代码参考HIT《数论及应用》
#include <cstdio> using namespace std; typedef long long LL; const int maxn=64; int bo[maxn],t; void divide(int m) { t=0; for(int i=2;i*i<=m;i++) if(m%i==0){ bo[++t]=i; while(m%i==0) m/=i; } if(m!=1) bo[++t]=m; } LL quick_multi(LL a,LL b) { LL ans=1; while(b) { ans*=a; b--; } return ans; } int n,m,a[maxn]; LL ans,temp; void dfs(int b,int ct,int c) { if(ct==c) { int x=m; for(int i=1;i<=c;i++) x/=a[i]; temp+=quick_multi(x,n); return ; } for(int i=b+1;i<=t;i++){ a[ct+1]=bo[i]; dfs(i,ct+1,c); } } int main() { while(~scanf("%d%d",&n,&m)){ divide(m); ans=0; for(int i=1;i<=t;i++){ temp=0; dfs(0,0,i); if(i&1) ans+=temp; else ans-=temp; } ans=quick_multi(m,n)-ans; printf("%lld\n",ans); } return 0; }