P4780 Phi的反函数 题解
bluewindde · · 题解
本题解是错解,详见 https://www.luogu.com.cn/discuss/988951
因为
注意需要先判掉
考虑优化:因为
此时
即
剪枝后,搜索实际上是枚举选 / 不选质因子,时间复杂度
实际实现中可以筛出一定范围内的质数,达到
#include <iostream>
#define int long long
using namespace std;
const int lim = 2e5;
const int mxx = 1ll << 31;
bool vis[lim + 5];
int pr[lim + 5], tail;
int n;
static inline bool isprime(int x) {
for (int i = 2; i * i <= x; ++i)
if (x % i == 0)
return false;
return true;
}
int ans = mxx + 1;
static inline void dfs(int x, int ph, int las, int dep) {
if (ph > n)
return;
if (x >= ans)
return;
if (ph == n)
ans = x;
if (n % ph)
return;
if (dep < 10)
for (int i = 1; i < las; ++i)
dfs(x * pr[i], ph * (pr[i] - 1), i, dep + 1);
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
for (int i = 2; i <= lim; ++i) {
if (!vis[i])
pr[++tail] = i;
for (int j = 1; j <= tail && i * pr[j] <= lim; ++j) {
vis[i * pr[j]] = true;
if (i % pr[j] == 0)
break;
}
}
cin >> n;
if (n == 1) {
cout << 1 << endl;
return 0;
}
if (isprime(n + 1)) {
cout << n + 1 << endl;
return 0;
}
dfs(1, 1, tail, 1);
if (ans > mxx)
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}