ZOJ 2739 & UVA 3399

思路:先離線求出[2,10000]的所有素數,再從素數數組從前往後累加求和

#include <iostream>

using namespace std;

bool isPrime(int x)
{
    if(2 >= x)
        return true;
    for(int i = 2; i < int(sqrt(double(x)))+1; i++)
    {
        if(0 == x % i )
            return  false;
    }
        return true;
}

int main()
{
    const int maxNum = 10000;
    int Primes[maxNum];
    int n = 0;
    for(int i = 2; i <= maxNum; i++)
    {
        if(isPrime(i))
            Primes[n++] = i;
    }
    int input;
    cin >> input;
    while(input != 0){
        int count = 0;
        for(int i = 0; Primes[i] <= input; i++)
        {
            int sum = 0;
            for(int j = i; Primes[j] <= input; j++)
            {
                sum += Primes[j];
                if(input == sum)
                    count++;
            }
        }
        cout << count <<endl;
        cin >> input;
    }
    for(int i = 0 ; i < 20 ; i++)
    {
        cout << Primes[i] << "\t";
    }   cout << endl;


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章