数论函数整理

· · 个人记录

筛法

试除法

过程

对于每个数使用试除法,从 [1, \lfloor \sqrt x\rfloor ] 中寻找 x 的因数。

经过 6k \pm 1 特判优化后可以达到时间复杂度 O(\frac{1}{3}\sqrt x) 以内判断一个数是否为质数。

筛出 [1,n] 范围内的质数总时间复杂度约为 O(\frac{1}{18} n\sqrt n) \approx O(0.056n\sqrt n),空间复杂度为 O(1)。

时限 1s 时最大数据范围为 10^6 左右。

代码

#include <bits/stdc++.h>
using namespace std;
inline bool zs(int x)
{
    if((x%6==1)||(x%6==5))
    {
        for(int i=1;(i*i*36-i*12)<x;++i)
        {
            if((x%(i*6-1)==0)||(x%(i*6+1)==0))
            {
                return 0;
            }
        }
        return 1;
    }
    return 0;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin>>n;
    if(n>=2)
    {
        cout<<2<<'\n';
        if(n>=3)
        {
            cout<<3<<'\n';
        }
    }
    for(int i=5;i<=n;i++)
    {
        if(zs(i))
        {
            cout<<i<<'\n';
        }
    }
    return 0;
}

埃拉托斯特尼筛法(埃氏筛)

过程

注意到试除法中尝试用合数来筛,而实际上我们只需要用质数来筛。因此考虑在一个数被判定为质数时将它的倍数打上标记,最终没被标记的就是质数。

时间复杂度 O(n \log \log n),空间复杂度 O(n)。

代码

欧拉筛(线性筛)

过程

代码