2

I'm given this algorithm and I'm told to find the complexity of it big theta.

for (i = 1; i <= n; i++) {
    j = n;
    while( j >= 1) {
        j = j/3;
    }

}

I know outer for loop runs n times. The while loop is more tricky though, Is it possibly log n (of base 3). In total making it n*log3n

Is this correct?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
TEDED
  • 21
  • 1

1 Answers1

0

There is an outer for loop of size n. It contributes a complexity of a factor of n to the over all complexity.

Let's say inner while loop runs for m times. After i'th iteration, the value of j will be n/(3^i). We will run this till n/(3^i) > 1. Therefore,

=> n/(3^i) = m
=> n = 3^m
=> log(n) = log2(3) * m
=> m = O(log(n))

So, for loop contributes to O(n) and while loop contributes to O(log(n)). Complexity of nested loop becomes O(n log(n)).

Mayank Jaiswal
  • 12,338
  • 7
  • 39
  • 41