跳到正文

个人记录

数论函数整理

Yuhaochen666约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年7月30日
收录
2026年7月30日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前

筛法

试除法

过程

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

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

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

时限 1s1s 时最大数据范围为 10610^6 左右。

代码

C++
#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(nlog⁡log⁡n)O(n \log \log n),空间复杂度 O(n)O(n)。

代码

C++

欧拉筛(线性筛)

过程

代码

C++
原文