poj2689 (prime interval sieve method template)

The meaning of problems: given an interval [l, r] wherein adjacent seeking the closest prime number and the farthest to where 1 <= l <r <= 2,147,483,647, r - l <= 1e6..

 

Thinking: prime number sieve interval

To find [l, r] recently and adjacent to the farthest primes certainly need to find out [l, r] all primes within. But whether it is a direct linear play table or violence are not handle that much data.

You can give prime numbers sqrt (r) to make a table, prime numbers sqrt (r) and then screened to [l, r] in a composite number, then traverse a [l, r], the answer to the recording.

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #define ll long long
 5 using namespace std;
 6 
 7 const int MAXN = 1e6 + 10;
 8 const int MAX = 1e5;
 9 int prime[MAX], tag[MAX], vis[MAXN], tot;
10 
11 void get_prime(void){
12     for(int i = 2; i < MAX; i++){
13         if(!tag[i]){
14             prime[tot++] = i;
15             for(int j = 2; j * i < MAX; j++){
16                 tag[j * i] = 1;
17             }
18         }
19     }
20 }
21 
22 ll Max(ll a, ll b){
23     return a > b ? a : b;
24 }
25 
26 int main(void){
27     get_prime();
28     ll l, r;
29     while(~scanf("%lld%lld", &l, &r)){
30         memset(vis, 0, sizeof(vis));
31         for(int i = 0; i < tot; i++){
32             ll a = (l + prime[i] - 1) / prime[i];
33             ll b = r / prime[i];
34             for(int j = Max(2, a); j <= b; j++){ // 筛[l, r]内的合数
35                 vis[prime[i] * j - l] = 1; // added back to Save a l when convenient labels, output answer 
36              }
 37 [          }
 38 is          IF (l == 1 ) VIS [ 0 ] = 1 ; // Note that this is not a prime number 
39          LL CNT = - 1 , SOL1 = MAXN, SOL2 = 0 , X1, Y1, X2, Y2;
 40          for ( int I = 0 ; I <= R & lt - L; I ++ ) {
 41 is              IF (VIS [I] == 0 ) {
 42 is                  IF (CNT! = - . 1 ) {
 43 is                      IF (SOL1> I - CNT) {
 44 is                         x1 = cnt;
45                         y1 = i;
46                         sol1 = i - cnt;
47                     }
48                     if(sol2 < i - cnt){
49                         x2 = cnt;
50                         y2 = i;
51                         sol2 = i - cnt;
52                     }
53                 }
54                 cnt = i;
55             }
56         }
57         if(sol2 == 0) puts("There are no adjacent primes.");
58         else printf("%lld,%lld are closest, %lld,%lld are most distant.\n", x1 + l, y1 + l, x2 + l, y2 + l);
59     }
60     return 0;
61 }
View Code

 

Guess you like

Origin www.cnblogs.com/ljy08163268/p/11704152.html