This article describes how to find 1 ~ Effective algorithms for all prime numbers in n --The sieve of Eratosthenes)To estimate the complexity of the algorithm and introduce its improvements --Linear Time screening method. The following content is not reprinted.
1. the sieve of Eratosthenes)
The hereshield screening method is an old method for filtering prime numbers. It is named by the ancient Greek mathematician heratosini. Because of its simple algorithm and ease of writing, it is widely used.
The algorithm concept is from 1 ~ In N, remove the multiples of 2, the multiples of 3 ,.......
Algorithm pseudo code:
$ A [I] $ indicates whether $ I $ is a prime number, which is true or false. Initialize $ A [2 \ cdots N] = true $.
For $ I = 2 $ to $ \ SQRT N $
If ($ A [I] $ is true)
For $ J = 2 $ to $ N/I $
$ A [I] $ = false;
End
End
End
Output:
All $ p $ S. T. $ A [p] $ is true
Because the sum of $ N $ must have a quality factor not greater than $ \ sqrt n $, the outer loop only needs to loop to $ \ sqrt n $
2. Estimation of the complexity of the eshield screening method
Complexity estimation can be considered as follows: When the outer loop is $ I $, the inner loop executes $ \ frac {n} {I} $ times. Therefore, the total time consumption is:
$ \ Sum _ {primes \, p \ Le \ SQRT n} \ frac {n} {p} = n \ sum _ {primes \, p \ Le \ SQRT n} \ frac {1} {p} $
AccordingMertens '2nd Theorem:
$ \ Lim _ {n \ To \ infty} \ sum _ {primes \ P \ Le n} \ frac {1} {p}-\ ln n = M $ $
$ M $ is the constant of meissel-Mertens, which is about $0.26 $
The algorithm time consumption is $ \ theta (n \ log n) $
Note: A small Optimization
You can start the inner loop from $ J = I $ instead of $ J = 2 $. This is because a sum must have been recorded when $ I $ is its smallest element, so you only need to consider the situation where $ J $ is larger than $ I $.
However, this optimization has not improved the complexity level. This is because for a prime factor that does not exceed $ \ frac {1} {2} n ^ {\ frac {1} {4} $, the above optimization only reduces the number of operations by half.
However, even if the sum limit is changed to $ \ frac {1} {2} n ^ {\ frac {1} {4} $, the order is still $ \ omega (n \ log n) $, so this is only a constant-level optimization.
3. Improvement of the escret method-linear time screening method
From the above analysis, we can see that the heresskey algorithm is not a linear time algorithm. In fact, the screening method has a simple improvement, reducing its complexity to linear time.
References:
Mertens '2nd Theorem:
Http://en.wikipedia.org/wiki/Mertens%27_theorems
Estimation and improvement of the complexity of the heratosini screening method and introduction to the linear time screening method