Problem Description
Z城市居住着很多只跳蚤。在Z城市周六生活频道有一个娱乐节目。一只跳蚤将被请上一个高空钢丝的正中央。钢丝很长,可以看作是无限长。节目主持人会给该跳蚤发一张卡片。卡片上写有N+1个自然数。其中最后一个是M,而前N个数都不超过M,卡片上允许有相同的数字。跳蚤每次可以从卡片上任意选择一个自然数S,然后向左,或向右跳S个单位长度。而他最终的任务是跳到距离他左边一个单位长度的地方,并捡起位于那里的礼物。
比如当N=2,M=18时,持有卡片(10, 15, 18)的跳蚤,就可以完成任务:他可以先向左跳10个单位长度,然后再连向左跳3次,每次15个单位长度,最后再向右连跳3次,每次18个单位长度。而持有卡片(12, 15, 18)的跳蚤,则怎么也不可能跳到距他左边一个单位长度的地方。
当确定N和M后,显然一共有M^N张不同的卡片。现在的问题是,在这所有的卡片中,有多少张可以完成任务。Input
两个整数N和M(N <= 15 , M <= 100000000)。
Output
可以完成任务的卡片数。
Sample Input
2 4
Sample Output
12
思路:
设卡片号为 a1,a2,...,an,m,跳蚤跳到对应号的次数是 x1,x2,...,xn,跳 m 个单位长度的次数是 xn+1
那么问题就转化为求:a[1]*x1+a[2]*x2+...+a[n]*xn+m*x(n+1)=1,一共有多少种情况
而上述公式实质是求:GCD(a1,a2,...,an,m)=1
故先对 m 进行素因子分解,求出总的排列组合个数,即有:m^n 种,再根据容斥定理排除公因子非 1 的情况即可
设 g 为公因子非 1 的情况数,f(i) 表示有 i 个公因子的情况数,根据奇加偶减,有:g=f(1)-f(2)+f(3)-...f(k)
如代码所示:
设g为公因子非1的情况数,f(i) 表示有 i 个公因子的情况数,由容斥原理得:g = f(1) - f(2) + f(3) -... f(k)
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 2000+5;
const int dx[] = {0,0,-1,1,-1,-1,1,1};
const int dy[] = {-1,1,0,0,-1,1,-1,1};
using namespace std;
LL n,m;
LL factor[N];
LL sum[N];
LL num,cnt;
void Get_Factor() { //分解质因子
num=0;
LL temp=m;
for(LL i=2; i*i<=temp; i++) {
if(temp%i==0) {
factor[num++]=i;
while(temp%i==0)
temp=temp/i;
}
}
if(temp!=1)
factor[num++]=temp;
}
LL quick_pow(LL a,LL b) {
LL r=1,base=a;
while(b) {
if(b&1)
r*=base;
base*=base;
b>>=1;
}
return r;
}
LL dfs(LL a,LL b,LL c) {//dfs得到卡片中n+1个数有c的公因子时的方法数
if(b==c) {
LL temp=m;
for(LL i=0; i<c; i++)
temp/=sum[i];//表示[1,x]中有多少个数是倍数
cnt+=quick_pow(temp,n);//选n个数,每个数x种选择
} else {
for(LL i=a; i<num; i++) {
sum[b]=factor[i];
dfs(i+1,b+1,c);
}
}
}
int main() {
while(scanf("%lld%lld",&n,&m)!=EOF&&(n+m)) {
Get_Factor();
LL res=quick_pow(m,n);//m^n
for(LL i=1; i<=num; i++) {
cnt=0;
dfs(0,0,i);
if(i%2)//奇加偶减
res-=cnt;
else
res+=cnt;
}
printf("%lld\n",res);
}
return 0;
}