【Aizu - ALDS1_1_C】Prime Numbers(素数筛法)

时间:2023-03-09 07:51:04
【Aizu - ALDS1_1_C】Prime Numbers(素数筛法)

Prime Numbers

 Descriptions:

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input

The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4

题目链接:

https://vjudge.net/problem/Aizu-ALDS1_1_C

题目大意:
输入n个数,判断里面有几个是素数,逐个枚举是最简单的但是会超时,这里用了一个简单的函数,以后可以套用

bool isprime(int x)
{
if(x==)
return true;
if(x<||x%==)
return false;
int i=;
while(i<=sqrt(x))
{
if(x%i==)
return false;
i+=;
}
return true;
}

 AC代码:

#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#define mod 1000000007
#define eps 1e-6
#define ll long long
#define INF 0x3f3f3f3f
#define ME0(x) memset(x,0,sizeof(x))
using namespace std;
bool isprime(int x)
{
if(x==)
return true;
if(x<||x%==)
return false;
int i=;
while(i<=sqrt(x))
{
if(x%i==)
return false;
i+=;
}
return true;
}
int n;
int main()
{
int total=;
int m;
cin>>n;
while(n--)
{
cin>>m;
if(isprime(m))
total++;
}
cout<<total<<endl;
}

这题比较简单,我之所以要为他写一篇博客,是因为一下这个埃拉托色筛选法:

1.列举大于等于2的整数

2.留下最小的整数2,删除所有2的倍数

3.在剩下的整数中留下最小的3,删除所有3的倍数

4.在剩下的整数中留下最小的5,删除所有5的倍数

5.以下同理,留下仍未被删除的最小的整数,删除该整数的倍数,一直循环到结束

int isprime[100005];
void eratos(int x)
{
for(int i=; i<=x; ++i)
isprime[i]=true;
isprime[]=isprime[]=false;
for(int i=; i<=x; ++i)
{
if(isprime[i])
{
int j=i+i;
while(j<=x)
{
isprime[j]=false;
j+=i;
}
}
}
}

这个是kuangbin的素数筛法,直接保存到数组,从1开始。

const int MAXN=;
int prime[MAXN+];
void getPrime()
{
memset(prime,,sizeof(prime));
for(int i=;i<=MAXN;i++)
{
if(!prime[i])prime[++prime[]]=i;
for(int j=;j<=prime[]&&prime[j]<=MAXN/i;j++)
{
prime[prime[j]*i]=;
if(i%prime[j]==)break;
}
}
}