Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexity of Loop Increment of 2

What is the time complexity of the following loop?

for(int i=1; i<=n; i=i*2){
    System.out.println("*");
}

is it logarithmic?

like image 412
JR Galia Avatar asked Oct 28 '25 06:10

JR Galia


2 Answers

The algorithm as shown would be O(log n)

Since the number of iterations would be log2(n), or log10(n)/log10(2)

like image 150
sehe Avatar answered Oct 30 '25 21:10

sehe


It's O(log n) because you are doubling the value of i on each iteration: 1, 2, 4, 8, ...

If n is 2x the loop will terminate after log2(2x) + 1 = x + 1 iterations.

like image 44
Mark Byers Avatar answered Oct 30 '25 20:10

Mark Byers