当前位置: 代码迷 >> 综合 >> POJ 2689 Prime Distance(区间相邻素数最大、小距离,区间素数筛)
  详细解决方案

POJ 2689 Prime Distance(区间相邻素数最大、小距离,区间素数筛)

热度:77   发布时间:2023-12-08 10:40:15.0

题目链接:
POJ 2689 Prime Distance
题意:
求出区间[a, b]内相邻素数的最大距离和最小距离。
分析:
区间素数筛。然后枚举所有区间素数。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 1000010;
const int INF = 0x3f3f3f3f;int prime_cnt;
int prime_list[MAX_N];
bool prime[MAX_N];void SegmentPrime(int L, int R)
{int len = R - L + 1;for(int i = 0; i < len; i++) { prime[i] = true; }int st = 0;if(L % 2) st++;for(int i = st; i < len; i += 2) { prime[i] = false; }int m = (int)sqrt(R + 0.5);for(int i = 3; i <= m; i += 2){if(i > L && prime[i - L] == false) continue;int j = L / i * i;if(j < L) j += i;if(j == i) j += i;j -= L;for(; j < len; j += i){prime[j] = false;}}if(L == 1) prime[0] = false;if(L <= 2) prime[2 - L] = true;prime_cnt = 0;for(int i = 0; i < len; i++){if(prime[i]) prime_list[prime_cnt++] = i + L;}
}int main()
{int a, b;while(~scanf("%d%d", &a, &b)){SegmentPrime(a, b);int Max = -1, Min = INF, lmin, rmin, lmax, rmax;for(int i = 1; i < prime_cnt; i++){if(prime_list[i] - prime_list[i - 1] < Min) {Min = prime_list[i] - prime_list[i - 1];lmin = prime_list[i - 1],  rmin = prime_list[i];}if(prime_list[i] - prime_list[i - 1] > Max){Max = prime_list[i] - prime_list[i - 1];lmax = prime_list[i - 1], rmax = prime_list[i];}}if(Max == -1) printf("There are no adjacent primes.\n");else {printf("%d,%d are closest, %d,%d are most distant.\n", lmin, rmin, lmax, rmax);}}return 0;
}
  相关解决方案