0

The following hypothetical function is a tricky one to calculate time complexity for. Not only is there recursion, but there are also for loops. The time complexity of calc() is $O(1)$.

void fun(int l, int r) {
    if(r-l+1<=1234) return;
    int m=(l+r)/2;
    int m1=(l+m)/2, m2=(m+1+r)/2;
    fun(l, m);
    fun(m1+1, m2);
    for(int k=1;k<=r-l+1;k++)
        for(int i=1;i<=r-l+1;i++)
            for(int j=l;j<=r;j+=i)
                calc(j, i);
    fun(m+1, r);
    fun(m1+1, m2);
}

Assuming the initial input is l=1, r=N, what is the Big-O time complexity of this function, as tightly bounded as possible? Please explain how I could get the answer.

RaymondY
  • 11
  • 2

2 Answers2

0

The initial loop runs in $n \times (n + n/2 + n/3 + n/4 + ...) = O(n^2 \log n)$, this form is used as a multiplier in the recursion.

Each recursion calls itself four times with the scope reduced by half after each call, we have $(1 \times (\frac{n}{1})^2 \log \frac{n}{1}) + (4 \times (\frac{n}{2})^2 \log \frac{n}{2}) + (16 \times (\frac{n}{4})^2 \log \frac{n}{4}) + ... + ((\frac{n}{4})^2 \times (\frac{n}{\frac{n}{4}})^2 \log \frac{n}{\frac{n}{4}}) + ((\frac{n}{2})^2 \times (\frac{n}{\frac{n}{2}})^2 \log \frac{n}{\frac{n}{2}}) + (n^2 \times (\frac{n}{n})^2 \log \frac{n}{n})$

$= n^2 \log \frac{n}{1} + n^2 \log\frac{n}{2} + n^2 \log \frac{n}{4} + ... + n^2 \log \frac{n}{\frac{n}{4}} + n^2 \log \frac{n}{\frac{n}{2}} + n^2 \log \frac{n}{n}$

$= n^2 (\log \frac{n}{1} + \log \frac{n}{2} + \log \frac{n}{4} + ... + \log \frac{n}{\frac{n}{4}} + \log \frac{n}{\frac{n}{2}} + \log \frac{n}{n})$

$= n^2 ((\log n - \log 1) + (\log n - \log 2) + (\log n - \log 4) + ... + (\log n - \log \frac{n}{4}) + (\log n - \log \frac{n}{2}) + (\log n - \log n))$

$= n^2 (\log^2n - \frac{1}{2} \log^2n) = O(n^2 \log^2n)$.

Kenneth Kho
  • 753
  • 3
  • 17
0

Hints:

  1. Define $D := r-l$ (there's honestly too many of it in the code, it should've jumped out to you immediately - also minus is rare in complexities)
  2. Look up Harmonic number
  3. Refresh your memory of Master Theorem

The answer falls out of these almost in no time with standard solving

(and in case you are confused by this, +1 near an input-controlled value is negligible)

NooneAtAll3
  • 280
  • 1
  • 8