POJ 2689 区间素数

#include 
#include 
const int maxn = 1E6 + 10;
int prime[maxn], primeLR[maxn], A, B;
bool vis[maxn];
void GetPrime()
{
	memset(prime, 0, sizeof(prime));
	for (int i = 2; i <= maxn; i++)
	{
		if (!prime[i]) prime[++prime[0]] = i;
		for (int j = 1; j <= prime[0] && prime[j] <= maxn / i; j++)
		{
			prime[prime[j]*i] = 1;
			if (i % prime[j] == 0) break;
		}
	}
}
void GetPrimeLR(int L, int R)
{
	memset(vis, 0, sizeof(vis));
	if (L < 2) L = 2;
	for (int i = 1; i <= prime[0] && (long long)prime[i]*prime[i] <= R; i++)
	{
		int s = L / prime[i] + (L % prime[i] > 0);
		if (s == 1) s = 2;
		for (int j = s; (long long)j * prime[i] <= R; j++)
			if ((long long)j * prime[i] >= L) vis[j * prime[i] - L] = 1;
	}
	primeLR[0] = 0;
	for (int i = 0; i <= R - L; i++)
		if (!vis[i]) primeLR[++primeLR[0]] = i + L;
}
int main(int argc, char const *argv[])
{
	GetPrime();
	while (~scanf("%d%d", &A, &B) && A + B)
	{
		GetPrimeLR(A, B);
		if (primeLR[0] < 2) printf("There are no adjacent primes.\n");
		else
		{
			int x1 = 0, x2 = 1E8, y1 = 0, y2 = 0;
			for (int i = 1; i < primeLR[0]; i++)
			{
				if (primeLR[i + 1] - primeLR[i] < x2 - x1)
					x1 = primeLR[i], x2 = primeLR[i + 1];
				if (primeLR[i + 1] - primeLR[i] > y2 - y1)
					y1 = primeLR[i], y2 = primeLR[i + 1];
			}
			printf("%d,%d are closest, %d,%d are most distant.\n", x1, x2, y1, y2);
		}
	}
	return 0;
}


给出一个区间[L,U],区间内相邻的距离最近的两个素数和距离最远的两个素数。

套用区间素数模板,暴力寻找。

你可能感兴趣的:(POJ 2689 区间素数)