2
int function2(int n)
{
    int i, j, k;
    int sum = 0;
    for (k = 1; k <= n; k += 1)
    {
        for (i = 1; i <= n; i *= 3)
        {
            j = i;
            while (j > 1)
            {
                sum += 1;
                j /= 3; 
            }
        } 
    }
    return sum; 
}

I understand that:

The outermost for loop runs n times. The inner for loop runs log3(n) times. The innermost while loop runs log3(i) times, and since i increases at a rate of log3(n), the while loop runs log3(log3(n)) times? So the total complexity is O(n * logn * log(logn))?

But thinking about it, wouldn't the while loop run the same number of times that i has been multiplied by 3? so couldn't we rewrite it as:

for (k = 1; k <= n; k++)
    for (i = 1; i <= log3(n); i++)
        for (j = 0; j < i; j++)

? in which case it'd be O(n * logn * logn)?

Someone also said it was O(n * logn) because it's a harmonic series? how is this a harmonic series?

Zhou Fang
  • 23
  • 3
  • "_and since i increases at a rate of log3(n), the while loop runs log3(log3(n)) times_": That's not how it works. You need to form the sum of `log3(i)` over all `i` that are iterated by the loop. These are all `i = 3^m` from `m=0` to `m=log3(n)`. `log3(3^m) = m`, so you are summing `m` from `0` to `log3(n)` which gives you a leading order `(log(n))^2`. This already accounts for both inner loops and you only need to multiply with the outer. (These are rough estimates, not a proper analysis for which you should find exact upper and lower bounds.) – user17732522 Mar 02 '23 at 20:31
  • @user17732522 I understood that the innermost while loop runs the number of times i gets multiplied by 3, or m=log3(n) times, each time, so the total complexity is O(nlognlogn)? – Zhou Fang Mar 02 '23 at 20:35
  • @ZhouFang Yes, your second line of reasoning in the question is correct. And for the last one "_how is this a harmonic series?_": It simply isn't. – user17732522 Mar 02 '23 at 20:38

1 Answers1

3

So the total complexity is O(n * logn * log(logn))?

No.

wouldn't the while loop run the same number of times that i has been multiplied by 3

Yes.

in which case it'd be O(n * logn * logn)?

Yes.

The inner most loop will loop log3 times for a given iteration of the middle loop, but is a power of 3, so actually with each next iteration of the middle loop, the inner loop will do one more iteration than before.

The number of inner loop iterations for the combined iterations of the middle loop -- for one outer iteration -- is the following sum:

      1 + 2 + 3 + ... + log3

This is a triangular number, and so this is O(log²).

Bringing the outer loop into the equation gives: O(log²)

trincot
  • 317,000
  • 35
  • 244
  • 286