acwing 196
作者:互联网
#include <bits/stdc++.h>
#define IOS ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define _zero(a) memset(a, 0, sizeof(a))
#define endl '\n'
#define int long long
#define mp make_pair
#define PII pair<int, int>
#define x first
#define y second
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define PII pair<int, int>
typedef long long ll;
typedef double dd;
typedef long double ld;
using namespace std;
const int inf = 1e10;
const int M = 998244353;
const ld pi = atan2(0, -1);//arctan(y/x);
const ld eps = 1e-8;
const int maxn = 5e5 + 100, N = 1e6 + 100;
int lp[maxn],primes[maxn],pcnt;
bool st[N];
void sieve()//线性筛
{
pcnt=0;
fill_n(lp,maxn,0);
for(int i=2;i<maxn;i++)
{
int& l=lp[i];
if(l==0)l=i,primes[pcnt++]=i;
for(int j=0;j<pcnt&&primes[j]<=l;++j)
{
int p=primes[j];
if(i*p>=maxn)break;
lp[i*p]=p;
}
}
}
signed main()
{
IOS;
int l, r;
sieve();
while (cin >> l >> r) {
memset(st, false, sizeof st);
if (l == 1) st[0] = true;
for (int i = 0; i < pcnt; i ++) {
int p = primes[i];
//aishai
int j = ((l + p - 1) / p);
if (j == 1) ++j;
j *= p;
for (; j <= r; j += p)
st[j - l] = true;
}
vector<int> a;
for (int i = l; i <= r; i ++) if (!st[i - l]) a.push_back(i);
int idx1 = -1, idx2 = -1, mn = INT_MAX, mx = 0;
if (a.size() < 2) {
printf("There are no adjacent primes.\n");
continue;
}
for (int i = 0; i < a.size() - 1; i ++) {
int k = a[i + 1] - a[i];
if (k > mx) {
idx2 = i;
mx = k;
}
if (k < mn) {
mn = k;
idx1 = i;
}
}
printf("%lld,%lld are closest, %lld,%lld are most distant.\n", a[idx1], a[idx1 + 1], a[idx2], a[idx2 + 1]);
//for (int i = l; i <= r; i ++) cout << st[i - l] << endl;
//for (int i : a) cout << i << endl;
//for (int i = 0; i < 100; i ++) cout << primes[i] << endl;
}
return 0;
}
标签:const,int,196,long,maxn,primes,acwing,define 来源: https://blog.csdn.net/ssd778/article/details/122564413