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