Home > Software engineering >  Finding time complexity of this loop?
Finding time complexity of this loop?

Time:06-15

What's time complexity of this loop?

R = 40;
while(R>=10){
  x = x-1;
  R = R div 2;
}

I really appreciate if you explain it to me, too.

CodePudding user response:

Each cycle the R is reduced to half.

Therefore O(log_2 R)


If R=40 cannot be changed, then the loop will just run 3 times therefore it is constant and O(1)

CodePudding user response:

Time complexity will be O(log2R).

Idea is that the R will get divided by 2 every time it enters the loop. R/2, R/22, R/23...

At some point R/2x = 10.
So which equates to 2x = (R/10)
and x = log2(R/10).

Since this appears to be close to log2R we can say its ~ O(log2R)

  • Related