How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?

Pre-requisite: Sieve of Eratosthenes

What is Sieve of Eratosthenes algorithm?
In order to analyze it, let’s take a number n and the task is to print the prime numbers less than n. Therefore, by definition of Sieve of Eratosthenes, for every prime number, it has to check the multiples of the prime and mark it as composite. This process continues until a value p which is the highest prime number less than n.

Understanding the n*log(log n) time complexity of Sieve of Eratosthenes

1. If it is assumed that the time taken to mark a number as composite is constant, then the number of times the loop runs is equal to:
2. On taking n common from the above equation, the above equation can be rewritten as:
$n*(\frac{1}{2}&space;+&space;\frac{1}{3}&space;+&space;\frac{1}{5}&space;+&space;\frac{1}{7}&space;+&space;......&space;p)$

3. It can be proved as below with the help of Harmonic Progression of the sum of primes:
$\frac{1}{2}&space;+&space;\frac{1}{3}&space;+&space;\frac{1}{5}&space;+&space;\frac{1}{7}&space;+&space;.....&space;=&space;log(log(n))$

Proof of Harmonic Progression of the sum of primes:
In order to understand the proof, the prerequisite is the Harmonic series and Taylor series expansion.

4. On substituting this in the equation, we get the time complexity as:
$O(n*(log(log(n))))$

Hence the time complexity of Sieve of Eratosthenes is n*log(log(n))

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.