题意:
给一张卡片,上面写着N + 1个自然数,其中最后一个数是M,并且前N个数不超过M,并允许数字相同。
一只跳蚤每次可以选择从卡片上任意选择一个自然数S,向左或向右跳S个单位长度。
求最后能跳到左边1个单位长度的N + 1元组个数是多少。
解析:
设卡片上的标号是a1,a2,a3,a4,...,an,M,跳蚤跳对应标号的次数为x1,x2,x3,x4,...,xn,x(n + 1)。
那么由题意可列出方程:a1*x1 + a2*x2 + a3*x3 + a4*x4 +... + an*xn + M*x(n + 1) = 1.
这个n+1元一次方程有解的充要条件是(a1,a2,a3,a4,...,an,M) = 1.
由于正面比较难刚,所以反面考虑,即所有的情况-各个数的gcd不为1的情况。
从M入手,若各个数最大公约数不为1,则各个数必存在一个或多个M的约数。
因此先将M的约数Pi分出来,然后应用斥容原理:
公约数不为1的数列个数 T = t(1) - t(2) + t(3) - t(4) + ...
其中t(n)代表数列中的数同时能被几个M的约数所约,比如t(2),是所有Pi中取2搭配,最后累加(M / (Pi × Pj))^ n.
(M / (Pi × Pj))^ n. 这个式子的解释是所有数小于M,除掉俩公约数就是剩下的数的最大值,因为可以重复取,这个数的^n就是不同数列的个数。
最后加加减减就是总的个数了。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
using namespace std;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = 4 * atan(1.0);
const double ee = exp(1.0);
const int maxn = 64;
LL n, m;
LL mCdNum;
LL mCd[maxn];
LL tCd[maxn];
LL resAns;
void Divide(LL x)
{
LL tempM = m;
mCdNum = 0;
for (LL i = 2; i * i <= tempM; i++)
{
if (tempM % i == 0)
{
while (tempM % i == 0)
{
tempM /= i;
}
mCd[++mCdNum] = i;
}
}
if (tempM != 1)
{
mCd[++mCdNum] = tempM;
}
}
LL myPow(LL a, LL x)
{
if (x == 0)
return 1;
LL r = myPow(a, x >> 1);
LL res = r * r;
if (x % 2)
res = res * a;
return res;
}
void Dfs(LL pos, LL deep, LL num)
{
if (deep == num)
{
LL tempM = m;
for (LL i = 1; i <= num; i++)
tempM /= tCd[i];
resAns += myPow(tempM, n);
}
else
{
for (LL i = pos + 1; i <= mCdNum; i++)
{
tCd[deep + 1] = mCd[i];
Dfs(i, deep + 1, num);
}
}
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
while (scanf("%lld%lld", &n, &m) == 2)
{
Divide(m);
LL ans = 0;
for (LL i = 1; i <= mCdNum; i++)
{
resAns = 0;
Dfs(0, 0, i);
if (i % 2)
ans += resAns;
else
ans -= resAns;
}
ans = myPow(m, n) - ans;
printf("%lld\n", ans);
}
return 0;
}