现在的位置: 首页 > 综合 > 正文

poj 2739 Sum of Consecutive Prime Numbers 小结

2014年07月06日 ⁄ 综合 ⁄ 共 1409字 ⁄ 字号 评论关闭
 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.

大意是,一个数可能可以拆成几个连续质数之和。有多组数据(以0结束),求 该数有几种拆法。
#include<stdio.h>
#include<cmath>
using namespace std;
long i,j,a[1230],n;
bool p(long k)
{
  for (long i=2;i<=trunc(sqrt(k));i++)
    if (k%i==0) return false;
  return true;
} 
int main()
{
  for (i=1;i<=1229;i++) a[i]=0;
  long cnt=1;a[cnt]=2;
  for (i=3;i<=10000;i++)
    if (p(i)){cnt++;a[cnt]=a[cnt-1]+i;}
  scanf("%ld",&n);
  while (n!=0)
  {
    long ans=0;
    for (i=1;i<=cnt;i++)
      for (j=i;j<=cnt;j++)
        {
          if (a[j]-a[i-1]==n) ans++;
          else if (a[j]-a[i-1]>n) break;
        }
    printf("%ld\n",ans);
    scanf("%ld",&n);
  }
  return 0;
} 

抱歉!评论已关闭.