质数
质数的定义:在大于1的整数中,如果只包含1和本身这两个约数就被成为质数或者叫做素数
试除法判定质数

#include <iostream>
#include <algorithm>
using namespace std;
//如果i能被n整除,那么d/i也一定可以被n整除
bool is_prime(int x)
{
    if (x < 2) return false;
    for (int i = 2; i <= x / i; i ++ )//所以这里写i<=d/i即可
        if (x % i == 0)               //不要写i*i<=n因为如果i比较大的时候,i*i就会溢出,变成一个负数影响最终答案
            return false;
    return true;
}
int main()
{
    int n;
    cin >> n;
    while (n -- )
    {
        int x;
        cin >> x;
        if (is_prime(x)) puts("Yes");
        else puts("No");
    }
    return 0;
}
 
分解质因数

#include <iostream>
#include <algorithm>
using namespace std;
void divide(int x)
{
    for (int i = 2; i <= x / i; i ++ )
        if (x % i == 0)
        {
            int s = 0;
            while (x % i == 0) x /= i, s ++ ;
            cout << i << ' ' << s << endl;
        }
    if (x > 1) cout << x << ' ' << 1 << endl;
    cout << endl;
}
int main()
{
    int n;
    cin >> n;
    while (n -- )
    {
        int x;
        cin >> x;
        divide(x);
    }
    return 0;
}
 
筛选质数

朴素做法
比如有 2,3,4,5,6,7,8,9,10,11,12
 这几个数
- 先把2的倍数删掉
 - 再把3的倍数删掉
 - 这样从小到大把所有数遍历一遍,删掉这个数的倍数
这样最后剩下没被删去的数就是质数
因为,如果从2~n中遍历一个数i,删除i的倍数,这样删到最后如果有个数p没被删去,那么从
2~p-1 一定都不是p的因子,所以这个数是质数 
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
bool st[N];//st中存的是这个数有没有被删除
int prime_num(int n){
    int cnt = 0;
    for(int i=2;i<=n;i++){
        if(!st[i]){//如果st[i]==false表示i这个数没有被删除,不是2~i-1任何一个数的倍数所以肯定是质数
            cnt++;
        }
        for(int j=i+i;j<=n;j+=i) st[j] = true;
    }
    return cnt;
}
int main()
{
    int n;
    cin >> n;
    cout << prime_num(n)<<endl;
    return 0;
}
 
优化版本
#include <iostream>
#include <algorithm>
using namespace std;
const int N= 1000010;
int primes[N], cnt;
bool st[N];
void get_primes(int n)
{
    for (int i = 2; i <= n; i ++ )
    {
        if (!st[i]) primes[cnt ++ ] = i;
        for (int j = 0; primes[j] <= n / i; j ++ )
        {
            st[primes[j] * i] = true;
            if (i % primes[j] == 0) break;
        }
    }
}
int main()
{
    int n;
    cin >> n;
    get_primes(n);
    cout << cnt << endl;
    return 0;
}










