The branch of mathematics called number theory is about properties of numbers. One of the areas that has captured the interest of number theoreticians for thousands of years is the question of primality. A prime number is a number that is has no proper factors (it is only evenly divisible by 1 and itself). The first prime numbers are 2,3,5,7 but they quickly become less frequent. One of the interesting questions is how dense they are in various ranges. Adjacent primes are two numbers that are both primes, but there are no other prime numbers between the adjacent primes. For example, 2,3 are the only adjacent primes that are also adjacent numbers.
Your program is given 2 numbers: L and U (1<=L< U<=2,147,483,647), and you are to find the two adjacent primes C1 and C2 (L<=C1< C2<=U) that are closest (i.e. C2-C1 is the minimum). If there are other pairs that are the same distance apart, use the first pair. You are also to find the two adjacent primes D1 and D2 (L<=D1< D2<=U) where D1 and D2 are as distant from each other as possible (again choosing the first pair if there is a tie).
Input
Each line of input will contain two positive integers, L and U, with L < U. The difference between L and U will not exceed 1,000,000.
Output
For each L and U, the output will either be the statement that there are no adjacent primes (because there are less than two primes between the two given numbers) or a line giving the two pairs of adjacent primes.
Sample Input
2 17
14 17
Sample Output
2,3 are closest, 7,11 are most distant.
There are no adjacent primes.
线性筛比一般的方法会快一点,莫比乌斯求系数不卡时间也是用这个。
因为
sqrt(1e9)<50000
s
q
r
t
(
1
e
9
)
<
50000
所以可以先把前面的一些求出来,因为给你的范围不大,用数组也能存的下,所以可以根据前面的来推出后面的素数。
#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
#define ll long long
ll nprime[50005],ctprim,prime1[1000005],prime2[1000005];
void isprime()
{
for(ll i=2;i<=50000;i++)
{
if(!nprime[i])
{
prime1[++ctprim]=i;
}
for(ll j=1;j<=ctprim&&prime1[j]*i<=50000;j++)
{
nprime[prime1[j]*i]=1;
if(i%prime1[j]==0)
break;
}
}
}
int main()
{
isprime();
ll l,r;
while(~scanf("%lld%lld",&l,&r))
{
if(l==1)
l=2;
for(ll i=0;i<=1000001;i++)
prime2[i]=1;
ll minf,mine,maxf,maxe;
ll pre=0;
ll maxn=-1e10,minn=1e10;
for(ll i=1;i<=ctprim&&prime1[i]<=sqrt(r);i++)
{
ll n=(l/prime1[i])+(l%prime1[i]>0?1:0);
if(n==1)
n=2;
for(ll j=n*prime1[i];j<=r;j+=prime1[i])
prime2[j-l]=0;
}
ll ans=0;
for(ll i=l;i<=r;i++)
{
if(prime2[i-l])
{
ans++;
if(ans>1)
{
if(i-pre<minn)
{
minf=pre;
mine=i;
minn=i-pre;
}
if(i-pre>maxn)
{
maxf=pre;
maxe=i;
maxn=i-pre;
}
}
pre=i;
}
}
if(ans<=1)
printf("There are no adjacent primes.\n");
else
printf("%lld,%lld are closest, %lld,%lld are most distant.\n",minf,mine,maxf,maxe);
}
return 0;
}