Prime Number screening (1) ESSD method, prime number
The principle is to first store all the numbers within 2-N in an array, Initialize all the numbers as prime numbers, and then start searching from 2, as long as the mark is a prime number, the mark of all its multiples is changed to a combination number, and so on. The time complexity is O (nloglogn ).
Code Implementation
1 void prime_table () 2 {3 for (int I = 2; (LL) I <= n; I ++) prime [I] = 1; 4 for (int I = 2; (LL) I * I <= n; I ++) 5 if (prime [I]) for (LL j = I * I; j <= n; j + = I) prime [j] = 0; 6}Prime screening
Interval prime screening
When the required range is too large, the above method will blow up the memory, so we can first make the tables of [2, √ B) and [a, B), in the screening [2, √ B) at the same time, divide the multiples in [a, B.
| Number of prime numbers in the 40027120 Interval |
| Difficulty level: B; running time limit: 1000 ms; running space limit: 262144KB; code length limit: 2000000B |
| Question description |
Given two integers a and B, calculate the number of prime numbers in the interval [a, B. |
| Input |
| A row contains two integers, a and B, separated by a space. |
| Output |
| A number indicates the number of prime numbers in the given range. |
| Input example |
| 22 37 |
| Output example |
| 3 |
| Other Instructions |
Data range: 1 ≤ a <B ≤ 10 ^ 12, B-a ≤ 10 ^ 7. Example: There are three prime numbers in total: 23, 29, and 31. |
1 # include <iostream> 2 using namespace std; 3 # define LL long 4 LL read () 5 {6 LL x = 0, f = 1; 7 char c = getchar (); 8 while (! Isdigit (c) {if (c = '-') f =-1; c = getchar ();} 9 while (isdigit (c )) {x = x * 10 + c-'0'; c = getchar ();} 10 return x * f; 11} 12 # define maxn 100001013 bool prime [maxn], is [maxn]; 14 LL a, B; 15 void prime_table () 16 {17 for (int I = 2; (LL) I * I <B; I ++) prime [I] = 1; 18 for (int I = 0; I <B-a; I ++) is [I] = 1; 19 for (int I = 2; (LL) I * I <B; I ++) if (prime [I]) {20 for (LL j = 2 * I; j * j <B; j + = I) prime [j] = 0; 21 for (LL j = max (2LL, (a + I-1)/I) * I; j <= B; j + = I) if (j> = a) is [j-a] = 0; 22} 23 return; 24} 25 26 int main () 27 {28 a = read (); B = read (); 29 prime_table (); 30 int cnt = 0; 31 for (int I = 0; I <B-; I ++) if (is [I]) cnt ++; 32 if (a = 1) cnt --; 33 printf ("% d \ n", cnt ); 34 35 return 0; 36}View Code