Sum of Consecutive Primes

Description

Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2+3+5+7+11+13, 11+13+17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime 

numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20. 

Your mission is to write a program that reports the number of representations for the given positive integer.

Input

The input is a sequence of positive integers each in a separate line. The integers are between 2 and 10 000, inclusive. The end of the input is indicated by a zero.

Output

The output should be composed of lines each corresponding to an input line except the last zero. An output line includes the number of representations for the input integer as the sum of one or more consecutive prime numbers. No other characters should be inserted in the output.

题目解释:对于一个数n,求其能够用顺序素数相加得到的情况数。如41,41 = 2+3+5+7+11,41=11+13+17,41=41,因此对于41有3种情况

解题思路:

(1)对于求解素数,可以使用筛选法求素数。例如求解1~100内的全部素数:首先排除1,然后用2除3~100的数,如果后面的数能够被2整除则说明该数不是素数,将该数删除。接着用3除剩下的数,以此类推,挖掉不是素数的数,剩下的就是素数了

(2)对于最终结果,也就是能够用顺序素数相加得到的情况数,使用逐个遍历的方法,不会超时。从第一个素数开始,往后相加,直到相加的和不小于该数,最后判断是否等于该数,要是相等,则说明是可行的。

#include <iostream>
#include <math.h>
#include <string.h>
#define MAX 10005
using namespace std;
bool isPrime[MAX];
int prime[MAX];
int prime_num;

void getPrime(){
    int maxV = sqrt(MAX);
    memset(isPrime, true, sizeof(isPrime));
    for (int i = 2; i < maxV; i++) {   // 使用筛选法求素数
        if (isPrime[i]) {
            for (int j = i+1; j < MAX; j++) {
                if (j%i == 0) {
                    isPrime[j] = false;
                }
            }
        }
    }
    prime_num = 0;
    for (int i = 2; i < MAX; i++) {  // 将所有的素数放在一个数组里面
        if (isPrime[i]) {
            prime[prime_num++] = i;
        }
    }
}
int main(int argc, const char * argv[]) {
    // insert code here...
    getPrime();
    int n;
    while (cin >> n) {
        if (n == 0 || n < 2 || n > 10000) break;
        int result = 0;
        for (int i = 0; i < prime_num; i++) {
            int sum  = prime[i];
            if (sum  > n) break;
            int j = i+1;      // 以第i个素数为起始点,开始进行顺序相加
            while (sum < n) {
                sum += prime[j++];
            }
            if (sum == n) {
                result ++;
            }
        }
        cout << result << endl;
    }
    return 0;
}


你可能感兴趣的:(算法,sicily)