Aizu - ALDS1_1_CPrime Numbers(素数筛法)

Posted sky-stars

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Aizu - ALDS1_1_CPrime 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

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

bool isprime(int x)

    if(x==2)
        return true;
    if(x<2||x%2==0)
        return false;
    int i=3;
    while(i<=sqrt(x))
    
        if(x%i==0)
            return false;
        i+=2;
    
    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==2)
        return true;
    if(x<2||x%2==0)
        return false;
    int i=3;
    while(i<=sqrt(x))
    
        if(x%i==0)
            return false;
        i+=2;
    
    return true;

int n;
int main()

    int total=0;
    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=0; i<=x; ++i)
        isprime[i]=true;
    isprime[0]=isprime[1]=false;
    for(int i=2; i<=x; ++i)
    
        if(isprime[i])
        
            j=i+i;
            while(j<=x)
            
                isprime[j]=false;
                j+=i;
            
        
    

 

以上是关于Aizu - ALDS1_1_CPrime Numbers(素数筛法)的主要内容,如果未能解决你的问题,请参考以下文章

Queue ,( Aizu - ALDS1_3_B )

Exhaustive Serch ( Aizu - ALDS1_5_A )

Aizu - ALDS1_4_C Dictionary

[Aizu] ALDS1_14_B: String Search[续]

Aizu - ALDS1_7_C Tree Walk

有根树的表达 Aizu - ALDS1_7_A: Rooted Trees