zoukankan      html  css  js  c++  java
  • nyoj 22-素数求和问题(打表)

    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
    ", cnt);
    45     }
    46     return 0;
    47 }
    
    
  • 相关阅读:
    [已解决] Python logging 重复打印日志信息
    scrapy
    Python 元编程
    MySQL性能优化 分区
    SQL Mode
    Golang 接口
    Python partial
    栈、队列(链表实现)
    Golang 位向量
    Java50题——学习以及思考
  • 原文地址:https://www.cnblogs.com/GetcharZp/p/9065158.html
Copyright © 2011-2022 走看看