prime distance (interval large number of internal quality

# The meaning of problems

Given two integers l, r, find the [l, r] the nearest pair of adjacent prime number, and the number of adjacent mass farthest from one pair of interval

l,r ∈ [1 , 231-1]

Where rl <= 1e6

# Explanations

L, a wide range of r, about 2e9 linear algorithm can not be determined [. 1, r] in all prime numbers, but a small range of rl,

Any engagement must contain a number of no more than √n prime factors, it is determined that all of the prime numbers 2 ~ √r,

For every prime number, and [l, r] in the aliquot of this figure mark, the rest is prime number within the range.

For pairwise comparison prime most value to

Complexity of O (√r * log (log r))

 1 #include <bits/stdc++.h>
 2 #define ll long long
 3 using namespace std;
 4 const int N=1e6;
 5 ll primes[N],cnt;
 6 bool st[N];
 7 bool rec[N];
 8 ll pri[N],num;//位于 l~r 之间的质数
 9 void get_primes(int n){
10     memset(st,false,sizeof st);
11     for(int i=2;i<=n;i++){
12         if(!st[i]) primes[cnt++] = i;
13         for(int j=0;primes[j]<=n/i;j++){
14             st[primes[j] * i]=true;
15             if(i % primes[j] ==0 ) break;
16         }
17     }
18 }
19 int main(){
20     ll l,r;
21     while(cin>>l>>r){
22         get_primes(sqrt(r));
23         memset(rec,false,sizeofREC);
 24          for (LL I = 0 ; I <CNT; I ++ ) {
 25              LL P = primes [I];
 26 is              for (LL J = max ( 2 * P, (L + p- . 1 ) / P * P ); J <= R & lt; J + = p) { // multiple is greater than the first p-l, the two cases,% p = 0 and p = 0%! 
27                  REC [JL] = to true ;
 28              }
 29          }
 30          NUM = 0 ;
 31 is          for ( int I = 0 ; I <= rl is an; I ++ ) {
 32              IF (! REC [I] && I + L> . 1 ) // 1不是质数特判
33                 pri[num++]=i+l;
34         }
35 
36         if(num<2) puts("There are no adjacent primes.");
37         else {
38             int mx=0,mn=0;
39             for(int i=0;i<num-1;i++){
40                 int d = pri[i+1]-pri[i];
41                 if(d > pri[mx+1] - pri[mx]) mx=i;
42                 if(d < pri[mn+1] - pri[mn]) mn=i;
43             }
44             printf("%d,%d are closest, %d,%d are most distant.\n",pri[mn],pri[mn+1],pri[mx],pri[mx+1]);
45         }
46     }
47 }

 

Guess you like

Origin www.cnblogs.com/hhyx/p/12601890.html