质数距离
本题提供了一种解决大数(1e8以上)区间中质数的方法.
对于\(x\in[L,R]\), \(x是合数\Longleftrightarrow 存在p\le50000且p\mid x,p<x\)
思路 :
- 先求出1~500000中质因子.
- 对于1~500000中的每个质因子p, 将[L,R]中所有p的倍数筛去(至少2倍).
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 1e6 + 7;
int p[N], cnt;
bool st[N];
void init() {
for (int i = 2; i < N; ++i) {
if (!st[i]) p[cnt++] = i;
for (int j = 0; p[j] * i < N; ++j) {
st[p[j] * i] = true;
if (i % p[j] == 0) break;
}
}
}
int main() {
//freopen("in.txt", "r", stdin);
//IO;
init();
int l, r;
while (cin >> l >> r) {
memset(st, 0, sizeof st);
for (int i = 0; i < cnt; ++i) {
ll t = p[i];
for (ll j = max(t * 2, (l + t - 1) / t * t); j <= r; j += t)
st[j - l] = 1;
}
vector<int> v;
for (int i = 0; i <= r - l; ++i)
if (!st[i] && i + l >= 2) v.pb(i + l);
//for (int i = 0; i < v.size(); ++i) cout << v[i] << ' ';
//cout << '\n';
if (v.size() <= 1) printf("There are no adjacent primes.\n");
else {
int mi = inf, mx = 0, ans1, ans2;
for (int i = 1; i < v.size(); ++i) {
int t = v[i] - v[i - 1];
if (t < mi) {
mi = t;
ans1 = i;
}
if (t > mx) {
mx = t;
ans2 = i;
}
}
printf("%d,%d are closest, %d,%d are most distant.\n", v[ans1 - 1], v[ans1], v[ans2 - 1], v[ans2]);
}
}
return 0;
}