Filtering of prime numbers in a given range (poj 2689)

Source: Internet
Author: User

Problem: Evaluate all prime numbers from L to R (L <r <= 2147483647, R-l <= 10 ^ 6)

Solution: To determine whether X is a prime number, check whether X % (all prime numbers smaller than X) has 0...

Of course, you can also optimize X % (all prime numbers smaller than SQRT (x)

Known SQRT (2147483647) = 49361;

The number of prime numbers in the range of [2, 49361] is less than 5000.

Then we use a prime number smaller than SQRT (r) to multiply the upper coefficient for enumeration. In this way, the multiplied number is not a prime number. Small the number of these screens, and the rest is the prime number.

How can we determine this coefficient? We can know that the lower limit of this coefficient is k = L/prime [I]. Of course, if Prime [I]> = L, K is initially 2. In fact, K * prime [I] must be greater than l and closest to L.

 

Table hitting:

CL (VIS,True);For(Ll I =2; I <n; ++I ){For(Ll J = LL (I) * LL (I); j <n; j + = I) vis [J] =False;} N=0;For(Ll I =2; I <n; ++I ){If(Vis [I]) {Prime [n++] =I ;}}

 

 

Screen out non-prime numbers:

 Void Get_p2 (ll l, ll R) {ll I; ll K;  If (R <n ){ //  If r <= 49361, you can directly use the original prime number table. I = 0  ;  While (Prime [I] <L) ++ I;  For (N2 = 0 ; Prime [I] <= r; ++ I) P2 [n2 ++] = Prime [I];  Return ;} Cl (VIS,  True  );  For (I = 0 ; I <n & prime [I] * prime [I] <= r; ++ I ){  If (Prime [I]> = L) k = 2  ;  Else  {K = L/ Prime [I];  If (K * prime [I] <L) ++K ;}  While (K * prime [I] <= R) {vis [K * Prime [I]-l] = False  ;  //  Printf ("% LLD % d \ n", K * prime [I], K * prime [I]-l, prime [I]); ++ K ;}} N2 = 0  ;  For (I = 0 ; I <= R-l; ++ I ){ If (Vis [I]) P2 [n2 ++] = I + L ;}} 

 

Given that the original prime number table has n prime numbers, the average number of K increases is ave (K), and the time complexity is O (n * ave (k ));

 

 

 

 

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.