【POJ】Sum of Consecutive Prime Numbers

题目

Sum of Consecutive Prime Numbers
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 28632 Accepted: 15358
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.
Sample Input

2
3
17
41
20
666
12
53
0
Sample Output

1
1
2
3
0
0
1
2

思路

先把需要用到的素数全都存起来,然后将连续的素数累加,如果和等于n。那么就算一次。计算完一次后,减掉前面的素数,然后继续向后试探,看看有没有别的组合方式使得加起来的和等于n。临界条件是要加的下一个素数大于n且此时sum的值还小于n(说明不能再往下面加了,否则即使减掉前面所有的素数也不会使得sum==n!),这时跳出循环。

代码

#include<stdio.h>
int num[2000];
int isPrime(int x);
int main(int argc, char const *argv[])
{
    int i,j=0;
    for(i = 2; i < 10000; i++){
        if(isPrime(i)){
            num[j++] = i;
        }
    }
    int n;
    while(~scanf("%d",&n)&&n){
        int sum = 2,cnt = 0,index = 0,l = 0;
        while(1){
            while(sum < n && num[index+1] <= n){
                sum += num[++index];
            }
            if(sum < n){
                break;
            }
            else if(sum > n){
                sum -= num[l++];
            }
            else{
                cnt++;
                sum -= num[l++];
            }
        }
        printf("%d\n",cnt);
    }
    return 0;
}
int isPrime(int x){
    int flag = 1;
    int i;
    if(x == 2)return 1;
    for(i = 2;i < x; i++){
        if(x % i == 0){
            flag = 0;
            break;
        }
    }
    return flag;
}

猜你喜欢

转载自www.cnblogs.com/zhaijiayu/p/9636683.html