2455: 【普及-】【P5736】质数筛

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:36 解决:19

题目描述

输入 lns="http://www.w3.org/1998/Math/MathML"> 个不大于 lns="http://www.w3.org/1998/Math/MathML">105 的正整数。要求全部储存在数组中,去除掉不是质数的数字,依次输出剩余的质数。

输入

第一行输入一个正整数 lns="http://www.w3.org/1998/Math/MathML">,表示整数个数。

第二行输入 lns="http://www.w3.org/1998/Math/MathML"> 个正整数 lns="http://www.w3.org/1998/Math/MathML">,以空格隔开。

输出

输出一行,依次输出 lns="http://www.w3.org/1998/Math/MathML"> 中剩余的质数,以空格隔开。

样例输入 复制

5
3 4 5 6 7

样例输出 复制

3 5 7

提示

数据保证,lns="http://www.w3.org/1998/Math/MathML">1100lns="http://www.w3.org/1998/Math/MathML">1105

#include<bits/stdc++.h>
using namespace std;
int a[110],n;
bool is_prime(int x) {
	if (x==0||x==1) return 0;
	//0和1都是质数,需要特判
	for(int i=2;i*i<=x;i++)
	//枚举2到sqrt(x),来判断x是否为质数
	    if(x%i==0)
		    return 0;
	return 1;//若是质数返回1,否则返回0 
}
int main(){
    cin>>n;
    for (int i=0;i<n;i++)
        cin>>a[i];
    for (int i=0;i<n;i++)
    	if (is_prime(a[i]))
    	    cout<<a[i]<<" ";
    cout<<endl;	
	return 0;
}