素数求和问题

来源:互联网 发布:阿里云rds数据库 编辑:程序博客网 时间:2024/05/07 19:10

素数求和问题
时间限制:3000 ms | 内存限制:65535 KB
难度:2
描述
现在给你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

题目地址:http://acm.nyist.net/JudgeOnline/problem.php?pid=22
问题分析:
主要是判断一个数是否为素数,一种方法是根据素数的定义,暴力遍历到sqrt(n),判断是否有除1和自身外可以整除的因子;另一种方法是预先找出素数,然后在找出的素数中判断是否有要判断的数。找素数可以使用素数筛选法。
代码:

#include <iostream>#include <stdio.h> #include <string.h>#include <math.h>#include <vector>#include <queue>#include <stack>#include <map>#include <string>#include <algorithm>#define MAX 1001using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop *///先利用素数筛选法筛选出1000之内的素数bool mark[MAX];int prime[MAX];int length=0;void findPrime(){    memset(mark,false,sizeof(mark));    for(int i=2;i<MAX;i++){        if(mark[i] == true){            continue;        }        mark[i]=true;        prime[length++]=i;        for(int j=i*i;j>0 && j<MAX;j+=i){            mark[j]=true;        }    }}bool isPrime(int x){    bool ans=false;    for(int i=0;i<length;i++){        if(prime[i] == x){            ans=true;            break;        }    }    return ans;}int n;int main(int argc, char** argv) {    //预处理 先找出MAX内的素数     findPrime();    cin>>n;    while(n--){        int m;        cin>>m;        int sum=0;        while(m--){            int tmp;            cin>>tmp;            if(isPrime(tmp) == true){                sum+=tmp;            }        }        cout<<sum<<endl;    }    return 0;}
原创粉丝点击