What is the runtime of the following pseudocode?
1 2 3 4 5 6 7 8 9 |
|
Details and Assumptions:
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
The key to solving this problem is to figure out what exactly it is doing!
We start with an array of booleans, all set to true. Then, any time we reach a number marked as true, we cross out all multiples of that number. So anything that is left is a number that isn't a multiple of any other number below it--a prime number.
So how long will this take?
The loop over i will execute n times, so all that remains is to find the complexity of the inner loop. We know that the inner loop will run about i N times. Since the inner loop is only running when i is prime by our reasoning above, we get a complexity of O ( n / 2 + n / 3 + n / 5 … ) = O ( n ( 1 / 2 + 1 / 3 + 1 / 5 … ) . Since the sum of all primes up to n roughly equals lo g lo g n , we get O ( n lo g lo g n ) .
A seasoned computer science student may also notice that this is the Sieve of Eratosthenes, and have recognized its runtime. You can read more about it: sieve of eratosthenes .