数学知识:筛选质数(埃氏筛法和线性筛法)

阅读 100

2022-02-06

埃氏筛法(比线性筛法慢一点):

const int N=1e5;

int pri[N],cnt;
bool st[N];

void screen(int n)
{
	st[1]=true;
	for(int i=2;i<=n;i++)
	{
		if(!st[i])
		{
			pri[cnt++]=i;
			for(int j=i+i;j<=n;j+=i)
				st[j]=true;
		}
	}
}

线性筛法:

const int N=1e5;

int pri[N],cnt;
bool st[N];

void screen(int n)
{
	st[1]=true;
	for(int i=2;i<=n;i++)
	{
		if(!st[i])
			pri[cnt++]=i;
		for(int j=0;j<=pri[j]/i;j++)
		{
			st[pri[j]*i]=true;
			if(i%pri[j]==0)
				break;
		}
	}
}

精彩评论(0)

0 0 举报