Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

O(n) runtime algorithm

The algorithm below has runtime O(n) according to our professor, however I am confused as to why it is not O(n log(n)), because the outer loop can run up to log(n) times and the inner loop can run up to n times.

Algoritme Loop5(n) 
i = 1 
while i ≤ n 
    j = 1 
    while j ≤ i 
       j = j + 1 
    i = i∗2
like image 331
Thomas B Avatar asked Apr 03 '16 09:04

Thomas B


People also ask

Which of the algorithms has a runtime of O log n?

A common algorithm with O(log n) time complexity is Binary Search whose recursive relation is T(n/2) + O(1) i.e. at every subsequent level of the tree you divide problem into half and do constant amount of additional work.

What is runtime in algorithm?

The running time of an algorithm refers to the length of time it takes for it to run as a function. An algorithm's running time for a given input depends on the number of operations executed. An algorithm with more operations will have a lengthier running time.

What is O log n in algorithm?

Logarithmic time complexity log(n): Represented in Big O notation as O(log n), when an algorithm has O(log n) running time, it means that as the input size grows, the number of operations grows very slowly.

Which algorithm has O 2 n time complexity?

Exponential Time — O(2^n) An algorithm is said to have an exponential time complexity when the growth doubles with each addition to the input data set. This kind of time complexity is usually seen in brute-force algorithms.


1 Answers

Your professor was right, the running time is O(n).

In the i-th iteration of the outer while-loop, when we have i=2^k for k=0,1,...,log n, the inner while-loop makes O(i) iterations. (When I say log n I mean the base-2 logarithm log_2 n.)

The running time is O(1+2+2^2+2^3+...+2^k) for k=floor(log n). This sums to O(2^{k+1}) which is O(2^{log n}). (This follows from the formula for the partial sum of geometric series.)

Because 2^{log n} = n, the total running time is O(n).

For the interested, here's a proof that the powers of two really sum to what I claim they sum to. (This is a very special case of a more general result.)

Claim. For any natural k, we have 1+2+2^2+...+2^k = 2^{k+1}-1.

Proof. Note that (2-1)*(1+2+2^2+...+2^k) = (2 - 1) + (2^2 - 2) + ... + (2^{k+1} - 2^k) where all 2^i for 0<i<k+1 cancel out, except for i=0 and i=k+1, and we are left with 2^{k+1}-1. QED.

like image 60
blazs Avatar answered Nov 05 '22 14:11

blazs