--------- prime number theory from

Given two integers L and U, you need the closed interval [L, the U-] to find the closest distance of two adjacent primes C1 and C2 (i.e., C2-C1 is the smallest), the other with the same distance if there o prime number pair, the output of the first pair.
At the same time, you also need to find the most distant two adjacent primes D1 and D2 (i.e., D1-D2 is the largest), the presence of other adjacent prime number if the same distance, the output of the first pair.
Input format
of each line of input two integers L and U, U and L wherein the difference does not exceed 1,000,000.
Output format
for each of the L and U, outputting a result, one row results.
The results include the number of the nearest neighbor and farthest quality of adjacent prime number pairs. (Refer to the specific format of the sample)
, if a prime number is not present between the L and U pair, the output "There are no adjacent primes." .
Data range
1≤L <U≤231-11≤L <U≤231-1
Input Sample:
2. 17
14. 17

Sample output:
2, 3 are Closest, 7, 11 are MOST Distant.
There are NO Adjacent primes.

Thinking: linear sieve selected only the number of 1-n, but to filter out a large number of now, according to the nature of each of a large number n exists a less root prime factors of n, the first filters out all prime factors of n 1 to the root, and then take these prime factors selected number of engagement within those ranges, and then sequentially enumerated Comparative

#include <cstring>
#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;
const int N = 1000010;
typedef long long LL;
int primes[N], cnt;
bool st[N];
void init(int n){
 memset(st, 0, sizeof st);
 cnt = 0;
 for (int i = 2; i <= n; i ++){
  if (!st[i])   primes[cnt ++] = i;
  for (int j = 0; primes[j] * i <= n; j ++){
   st[i * primes[j]] = true;
   if (i % primes[j] == 0)   break;
  }
 }
}
int main(){
 int l, r;
 while(cin >> l >> r){
  init(50000);
  memset(st, 0, sizeof st);
   for(int i = 0; i < cnt; i ++){
   LL p = primes[i];
   for (LL j = max(2 * p, (l + p - 1) / p * p); j <= r; j += p)
   st[j - l] = true;
  }
   cnt = 0;
    for (int i = 0; i <= r - l; i ++)
   if (!st[i] && i + l >= 2)
   primes[cnt ++] = l + i;
    if (cnt < 2)   puts("There are no adjacent primes.");
   else{
    int minp = 0, maxp = 0;
    for (int i = 0; i + 1 < cnt; i ++){
     int d = primes[i + 1] - primes[i];
     if (d < primes[minp + 1] - primes[minp])   minp = i;
     if (d > primes[maxp + 1] - primes[maxp])   maxp = i;
    }
         printf("%d,%d are closest, %d,%d are most distant.\n",
                primes[minp], primes[minp + 1],
                primes[maxp], primes[maxp + 1]);
   }
 }
 return 0;
}
Published 106 original articles · won praise 67 · views 5430

Guess you like

Origin blog.csdn.net/qq_45772483/article/details/104940293