程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Uva 10168 Summation of Four Primes 素數

Uva 10168 Summation of Four Primes 素數

編輯:C++入門知識

[cpp] 
/*
*   Status: 10540903    10168   Summation of Four Primes    Accepted    C++ 0.864   2012-08-30 02:49:48
*   url:  http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1109
*   Time: 2012.8.30 10:30 around
*   Stratege: 通過打表,發現奇數是2,3開始的,偶數是2,2開始的,所以只要一層循環,就可以了
*
*/ 
#include <iostream> 
#include <cstdio> 
#include <cmath> 
#include <algorithm> 
#include <cstring> 
#include <queue> 
using namespace std ; 
 
#define LL long long 
#define MAXN  10000000 
int p[MAXN], prilen ; 
bool NotPrime[MAXN] ; 
int n ; 
 
void getPrime () 

    int i, j ; 
    for (i = 4; i < MAXN; i += 2) 
        NotPrime[i] = true ; 
    NotPrime[0] = NotPrime[1] = true ; 
    prilen = 1 ; 
    p[0] = 2 ; 
    for (i = 3; i < MAXN; i += 2) 
    { 
        if (!NotPrime[i]) 
        { 
            p[prilen++] = i ; 
            for (j = 2*i; j < MAXN; j += i) 
                NotPrime[j] = true ; 
        } 
    } 

 
int main () 

    getPrime () ; 
    int i ; 
    while (scanf ("%d", &n) != EOF) 
    { 
        if (n < 8) 
        { 
            printf ("Impossible.\n") ; 
            continue ; 
        } 
        if (n % 2 == 0) 
        { 
            printf ("2 2 ") ; 
            n -= 4 ; 
            for (i = 0; i < prilen; i ++) 
            { 
                if (!NotPrime[p[i]] && !NotPrime[n-p[i]]) 
                { 
                    printf ("%d %d\n", p[i], n-p[i]) ; 
                    break ; 
                } 
            } 
        } 
        else if (n % 2) 
        { 
            printf ("2 3 ") ; 
            n -= 5 ; 
            for (i = 0; i < prilen; i ++) 
            { 
                if (!NotPrime[p[i]] && !NotPrime[n-p[i]]) 
                { 
                    printf ("%d %d\n", p[i], n-p[i]) ; 
                    break ; 
                } 
            } 
        } 
    } 
    return 0 ; 

//打表代碼 
/*
int main ()
{
    getPrime () ;
    int i, j, k, l, q ;
    for (i = 100; i < 200; i ++)
    {
        for (j = 0; p[j] < i; j ++)
            for (k = 0; p[k] < i; k ++)
                for (q = 0; q < i; q ++)
                {
                    if (!NotPrime[i-p[j]-p[k]-p[q]] && i-p[j]-p[k]-p[q] >= 2)
                    {
                        cout << i << " " << p[j] << " " << p[k] << " " << p[q] << " " << i-p[j]-p
                            [k]-p[q] << endl ; 
                        goto L ;
                    }
                }
        cout << i << " " << "impossible" << endl ;
L:      continue ;
    }
    cin >> q; 
    return 0 ;
}
*/ 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved