简体   繁体   中英

Time complexity of recursive function find(n)

void find (int n) {
    if (n < 2) return;
    else {
        sum = 0;

        for (i = 1; i <= 4; i++) find(n / 2); 
        for (i = 1; i <= n*n; i++)
            sum = sum +1;
    }
}

Assume that the division operation takes constant time and sum is a global variable. What is the time complexity of find(n) ?

According to me: Since first for loop run 4 log n times and second for loop run n^2 times. So the total time complexity = O(4 log n + n^2) = O(n^2) .

T(n) = 4 * T(n/2) + O(n^2)
a = 4, b = 2, f(n) = n^2
f(n) = O(n^c log^k(n)) , c = 2, k = 0
logb(a) = log2(4) = 2, c = logb(a)
T(n) = Theta(n^(logb(a))log^(k+1)n) = Theta(n^2*log^1(n)) = Theta(n^2*log(n))

Case 2 of the master theorem. https://en.wikipedia.org/wiki/Master_theorem

The first loop excutes O(log(n)) times, each time calling itself. Upon returning, each invocation will invoke a O(n^2) loop.

Therefore, O(n^2 log(n))

You are correct. n^2 + (n/2)^2 + (n/4)^2 + .. is in O(n^2) because it is less than 2*(n^2). You can fill all smaller squares in larger one.

This would hold even if there would be O(n) as last loop.

For example

for (i = 1; i <= 4; i++) find(n / 2); 
for (i = 1; i <= n; i++)
    sum = sum +1;

has complexity of O(n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM