POJ2689 Prime distance - 筛法
Posted zolrk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ2689 Prime distance - 筛法相关的知识,希望对你有一定的参考价值。
这是一道非常典型的筛法,利用区间长度比较小,以及质数比较少,用少量的质数,只筛区间内部的合数,复杂度就不会很高
建议多开long long,很多时候你难以注意到哪里会爆int
还有就是可以自己估摸着数量级提前把素数表打完,别每次都重打一遍素数表
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <cmath>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
const int MAXN = 1000000 + 10;
typedef long long ll;
ll l,r,max_ans,min_ans,l1,r1,l2,r2,tot,n,cnt;
ll prime[MAXN],vis[MAXN];
void primes(int n) {
memset(vis, 0, sizeof(vis));
memset(prime, 0, sizeof(prime));
tot = 0;
for(int i=2; i<=n; i++) {
if(!vis[i]) prime[++tot] = i;
for(int j=1; j <= tot && prime[j]*i <= n; j++) {
vis[i*prime[j]] = 1;
if(i % prime[j] == 0) break;
}
}
}
int main() {
primes(1e5);
while(scanf("%lld%lld", &l, &r) != EOF) {
if(l == 1) l = 2;
memset(vis, 0, sizeof(vis));
max_ans = 0, min_ans = 1 << 30;
for(int i=1; i<=tot; i++) {
int now = prime[i];
for(int j = l/now; j <= r/now; j++) {
ll val = j * now;
if(val < l || j <= 1) continue;
int pos = val - l;
vis[pos] = 1;
}
}
cnt = 0;
ll last = -1, max_ans = 0, min_ans = 1<<30;
for(int i=0; i<=r-l; i++) {
if(!vis[i]) {
if(last != -1) {
if(max_ans < i - last) {
max_ans = i - last;
l1 = last, r1 = i;
}
if(min_ans > i - last) {
min_ans = i - last;
l2 = last, r2 = i;
}
}
last = i;
}
}
if(!max_ans)
printf("There are no adjacent primes.
");
else
printf("%lld,%lld are closest, %lld,%lld are most distant.
", l2 + l, r2 + l, l1 + l, r1 + l);
}
return 0;
}
以上是关于POJ2689 Prime distance - 筛法的主要内容,如果未能解决你的问题,请参考以下文章
POJ-2689-Prime Distance(素数区间筛法)