POJ 2739 Sum of Consecutive Prime Numbers (Prime number)

Source: Internet
Author: User

POJ 2739 Sum of Consecutive Prime Numbers (Prime number)

POJ 2739 Sum of Consecutive Prime Numbers (Prime number)

 

Question:

I will give you a natural number X of less than 10000, and then ask you how many methods can this number x be obtained by adding continuous prime numbers?

Analysis:

First, we use the prime number embedding method to retrieve all the prime numbers within 10000 and store them in the prime array from small to large.

Then find the upper bound of number X in prime. If the sum of consecutive prime numbers = X, it must start from a prime number smaller than X (It cannot exceed the upper limit of X) Until the sum value is greater than or equal to X.

Therefore, we enumerate all possible prime numbers within 10000 plus the start point I, and then calculate the sum of continuous prime numbers, check whether the continuous prime number starting with prime [I] is equal to or equal to X.

Since there are very few prime numbers within 10000 (only more than 1000), we can find continuous prime numbers and solve them by brute force enumeration.

AC code:

 

# Include
 
  
# Include
  
   
Using namespace std; const int maxn = 10000; // evaluate the prime number using the int prime [maxn + 5]; int get_prime () {memset (prime, 0, sizeof (prime )); for (int I = 2; I <= maxn; I ++) {if (! Prime [I]) prime [++ prime [0] = I; for (int j = 1; j <= prime [0] & prime [j] <= maxn/I; j ++) {prime [prime [j] * I] = 1; if (I % prime [j] = 0) break;} return prime [0];} int main () {// preprocessing: evaluate all prime numbers less than 10000 get_prime (); int x; while (scanf (% d, & x) = 1 & x) {if (x <2) {printf (0); continue;} int bound = lower_bound (prime + 1, prime + prime [0] + 1, x)-prime; int ans = 0; if (prime [bound] = x) ans ++; for (int I = 1; I
   
    

 

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.