Hit 2276 (number theory, prime number )]

Source: Internet
Author: User

Hit 2276 (number theory, prime number )]

 

[Original question link]

Http://acm-hit.sunner.cn/index.php? Option = com_wrapper & Itemid = 39

(Not accurate. You need to go to hit to find the question number)

 

[Topic]

Number of prime numbers between input L, R output L, and R (L <= r <= 2147483647, R-l <= 1000000)

 

[Solution Thinking]

The data range is relatively large. We need to make full use of the method to determine the prime number. We can know that if a number X is not a prime number, and only if there is a number y less than or equal to SQRT (x, so that X % Y = 0, so SQRT (2147483647) can be used to make the overall judgment, because the R-L has a range, therefore, we can traverse the number sieve in this range to remove a multiple of the prime numbers smaller than SQRT (R). What is not screened is the prime number. Just traverse the number of prime numbers.

 

[Code]

# Include <iostream>

# Include <cmath>

Using namespace STD;

 

Unsigned long prime (unsigned long a [], unsigned long N)

{

Unsigned long I, J, K, X, num, * B;

N ++;

N/= 2;

B = new unsigned long [(n + 1) * 2];

A [0] = 2; A [1] = 3; num = 2;

For (I = 1; I <= 2 * n; I ++)

B [I] = 0;

For (I = 3; I <= N; I + = 3)

For (j = 0; j <2; j ++)

{

X = 2 * (I + J)-1;

While (B [x] = 0)

{

A [num ++] = X;

For (k = x; k <= 2 * n; k + = X)

B [k] = 1;

}

}

Return num;

}

 

Unsigned long PR [50000];

Bool ishave [1100000];

 

Int main ()

{

Unsigned long l, R, I, j, ans;

Prime (PR, 50000 );

While (scanf ("% LD % lD", & L, & R )! = EOF)

{

Ans = 0;

For (I = 0; I <= R-l; I ++) ishave [I] = 1;

For (I = 0; PR [I] * PR [I] <= r; I ++)

{

If (L % PR [I]) J = (L/PR [I] + 1) * PR [I];

Else J = L;

For (; j <= r; j + = Pr [I])

{

If (J! = Pr [I]) ishave [J-L] = 0;

}

}

For (I = 0; I <= R-l; I ++)

If (ishave [I]) ans ++;

Printf ("% LD \ n", ANS );

}

Return 0;

}

[\ Code]

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.