Tricky Looping

What is the Big-O Notation of the following code snippet?

1
2
3
4
5
6
product_prices = [10.25, 10.99, 11.50, 16.99]

n = len(product_prices)
while n > 0:
   print(product_prices[n-1])
   n = int(n / 2)

O ( n / 2 ) O(n/2) O ( l o g 2 ( n ) ) O(log_{2}(n)) O ( n ) O(n) O ( n 2 ) O(n^{2})

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.

1 solution

John Faucett
Oct 13, 2019

As the input size n n grows the number of steps taken by the while loop grows logarithmically.

We can see this by observing the number of times the while loop is executed for different n n values for the input list product_prices .

n = len(product_prices) number of times while loop runs
4 3
8 4
16 5
32 6
64 7

It is even possible to see the logarithmic growth rate, without observation. A repeated multiplication is an exponential growth. A repeated division is the inverse operation and therefore is must be a logarithmic growth.

CodeCrafter 1 - 1 year, 7 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...