判断质数和给定范围内质数的筛选(埃氏筛法)

判断质数代码

#include<iostream>
using namespace std;

bool judge (int x) {
    for (int i = 2; i * i <= x; i++) {
        if (x % i == 0) return false;
    }
    return true;
}

int main()
{
    int n;
    cin>>n;
    while (n--) {
        int x;
        cin >> x;
        if (judge(x)) cout << x << " is prime" << endl;
        else cout << x << " is not prime" << endl;
    }
    return 0;
}

埃氏筛法——素数的快速筛选

埃氏筛法的的核心是: 素数的倍数都不是素数,如下图:

代码如下:

#include <iostream>
#include
<cstring> using namespace std; const int N = 1e6 + 10; bool st[N]; // 素数表,如果是质数,则为true int prime (int n) { memset (st, 1, sizeof(st)); // 初始化都为true   
  int cnt = 0; for (int i = 2; i <= n; i++) { if (st[i]) { cnt++; for (int j = i; j <= n; j += i) { //用当前的质数筛选出非质数 st[j] = false; } } } return cnt; } int main() { int n; cin >> n; cout << prime (n) << endl; return 0; }
posted @ 2022-09-12 17:43  !&&||  阅读(60)  评论(0)    收藏  举报