传送门
Solution
设第一次操作的结果为 x,选定的素数为 p1。第二次操作的结果为 y,选定的素数为 p2。由题意可得
x−p1+1≤y−p2<x≤y
题目给出的是 y,所求为 x−p1+1 的最小值。要使 x 最小,则要使 y−p2 最小。因此找出 y 的最大质因数。再枚举 p1,求出符合上文不等式的最小合法 x,可找出答案。
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #include <bits/stdc++.h> #define N 1000010 using namespace std; typedef long long ll;
template <typename T> inline void read(T &x) { x = 0; T f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -f; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} x *= f; }
int n, pri[N], cnt, ans = 1e9, a, b, c, d, ida; bool isp[N], flg;
void prime() { for (int i = 2; i <= 1e6; i++) { if (!isp[i]) pri[++cnt] = i; for (int j = 1; pri[j] * i <= 1e6; j++) { isp[pri[j] * i] = 1; if (i % pri[j] == 0) break; } } }
int main() { read(n); prime(); for (int i = 1; pri[i] < n; i++) if (n % pri[i] == 0) a = pri[i]; if (!a) { printf("-1"); return 0; } b = n - a; for (int i = 1; pri[i] * 2 <= n; i++) if ((b / pri[i] + 1) * pri[i] <= n) ans = min(ans, (b / pri[i]) * pri[i] + 1); if (ans == 1e9) printf("-1"); else printf("%d", ans); return 0; }
|