「学习笔记」Eratosthenes筛法

Eratosthenes筛法是求1~n中的素数的筛法

从2开始,把其倍数(从2倍开始)剔除,剩下的即素数

 

#include 
using namespace std;

bool p[100001]; //p[i]=true 表示i是素数
int n, tot;

int main() {
	cin >> n;
	for(int i=2; i<=n; i++) p[i] = true;
	for(int i=2; i<=n; i++)
		for(int j=i*2; j<=n; j+=i) p[j] = false;
	for(int i=2; i<=n; i++) if(p[i]) tot ++;
	cout << tot << endl;
	return 0;
}

 

优化1:实际上,若i不是素数,可以不剔除其倍数,其倍数已经被其因数剔除

     for(int i=2; i<=n; i++)
        if(p[i]) for(int j=i*2; j<=n; j+=i) p[j] = false; //p[i]是素数时剔除

 

优化2:只要筛到n的算数平方根就行了(2~n的算数平方根中无因数,即为素数)

     n = sqrt(n+0.5);

 

优化3:不必从i*2开始筛,在i=2时筛过;也不必在i*3时开始..;不必从i*(i-1)时开始;就从i*i开始!

for(int i=2; i<=n; i++)
        if(p[i]) for(int j=i*i; j<=n; j+=i) p[j] = false;

 

(时间上)最优代码:

复杂度: $O(n log log n)$

#include 
#include 
using namespace std;

bool p[100001];
int n, sn, tot;

int main() {
	cin >> n;
	sn = sqrt(n+0.5);
	for(int i=2; i<=n; i++) p[i] = true;
	for(int i=2; i<=sn; i++)
		if(p[i]) for(int j=i*i; j<=n; j+=i) p[j] = false;
	for(int i=2; i<=n; i++) if(p[i]) tot ++;
	cout << tot << endl;
	return 0;
}


0.0 --

 

 

 

你可能感兴趣的:(「学习笔记」Eratosthenes筛法)