nyoj 22-素數求和問題(打表)
阿新 • • 發佈:2018-05-21
數據 描述 OS c++代碼 queue badge 核心 ostream strong
22-素數求和問題
內存限制:64MB
時間限制:3000ms
Special Judge: No
accepted:41
submit:52
題目描述:
現在給你N個數(0<N<1000),現在要求你寫出一個程序,找出這N個數中的所有素數,並求和。輸入描述:
第一行給出整數M(0<M<10)代表多少組測試數據 每組測試數據第一行給你N,代表該組測試數據的數量。 接下來的N個數為要測試的數據,每個數小於1000
輸出描述:
每組測試數據結果占一行,輸出給出的測試數據的所有素數和
樣例輸入:
3 5 1 2 3 4 5 8 11 12 13 14 15 16 17 18 10 21 22 23 24 25 26 27 28 29 30
樣例輸出:
10 41 52
分析:
將1000以內的每一個數據打表判斷是否是素數,素數標記為0,非素數標記為1;
核心代碼:
1 void cal_excel() // 打素數表 2{ 3 for(int i = 2; i <= MAXN; ++ i) 4 { 5 if(!excel[i]) 6 { 7 for(int j = 2; ; ++ j) 8 { 9 int temp = i * j; 10 if(temp >= MAXN) break; 11 excel[temp] = 1; 12 } 13 } 14 }15 }
C/C++代碼實現(AC):
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <cstdio> 5 #include <cmath> 6 #include <stack> 7 #include <map> 8 #include <queue> 9 10 using namespace std; 11 const int MAXN = 1005; 12 int excel[MAXN] = {1, 1}; 13 14 void cal_excel() 15 { 16 for(int i = 2; i <= MAXN; ++ i) 17 { 18 if(!excel[i]) // 為0代表素數 19 { 20 for(int j = 2; ; ++ j) 21 { 22 int temp = i * j; 23 if(temp >= MAXN) break; 24 excel[temp] = 1; 25 } 26 } 27 } 28 } 29 30 int main() 31 { 32 cal_excel(); 33 int t; 34 scanf("%d", &t); 35 while(t --) 36 { 37 int n, cnt = 0, temp; 38 scanf("%d", &n); 39 for(int i = 0; i < n; ++ i) 40 { 41 scanf("%d", &temp); 42 if(!excel[temp]) cnt += temp; 43 } 44 printf("%d\n", cnt); 45 } 46 return 0; 47 }
nyoj 22-素數求和問題(打表)