poj 2739 Sum of Consecutive Prime Numbers

//题目给出一个数,让你求连续的素数相加的和等于这个数的字串个数!(要求是连续的)
//例如 41  41 = 2 + 3 + 5 + 7 + 11 + 13  41 = 11 + 13 + 17  41 = 41 这样的素数字串有3个 
#include "iostream"
#include "cmath"
#include "memory.h"
using namespace std;

int primer[5000];

bool is_primer(int num)
{
     int i;
     if (num == 1) 
         return false;
     else
     {
         int n = sqrt(double(num));
         for (i = 2; i <= n; i++)
         {
             if (num % i == 0)
                 return false;
         }
         return true;
     }
}

/*
//筛子法求素数 
void is_primer()
{
     int num[100000000];
     memset(num, 1, sizeof(num));
     int i, j;
     num[0] = 0, num[1] = 0;
     for (i = 2; i < 100000000; i++)
     {
         if (num[i])
         {
             for (j = i * 2; j < 100000000; j += i)
                 num[j] = 0;
         }
     }
}
*/

int main()
{
    int i, j, k, num, count, sum;
    bool flag;
    memset(primer, 0, sizeof(primer));
    for (i = 1, j = 0; i <= 10000; i++)
    {
        if (is_primer(i))
        {
           primer[j] = i;
           j++;
        }
    }
    while (cin >> num && num)
    {
          count = sum = 0;
          flag = false;
          for (i = 0; i < j; i++)
          {
              sum = 0;
              if (flag)  break;
             for (k = i; k < j; k++)
             {
                 if (primer[k] > num)
                 {
                    flag = true;
                    break;
                 }
                 sum += primer[k];
                 if (sum == num)
                 {
                    count++;
                    break;
                 }
                 if (sum > num)
                    break;
             }
          }
          cout << count << endl;
    }
    //system("pause");
}

你可能感兴趣的:(Numbers)