tags:

views:

295

answers:

2

What is the time and space complexity of:

int superFactorial4(int n, int m)
{
    if(n <= 1)
    {
        if(m <= 1)
            return 1;
        else 
            n = m -= 1;
    }

    return n*superFactorial4(n-1, m);
}

It runs recursively by decreasing the value of n by 1 until it equals 1 and then it will either decrease the value of m by 1 or return 1 in case m equals 1.

I think the complexity depends on both n and m so maybe it's O(n*m).

A: 

The time complexity is O(n+m^2), space complexity the same.

Reasoning: with a fixed value of m, the function makes n recursive calls to itself, each does constant work, so the complexity of calls with fixed m is n. Now, when n reaches zero, it becomes m-1 and m becomes m-1 too. So the next fixed-m-phase will take m-1, the next m-2 and so on. So you get a sum (m-1)+(m-2)+...+1 which is O(m^2).

The space complexity is equal, because for each recursive call, the recursion takes constant space and you never return from the recursion except at the end, and there is no tail recursion.

jpalecek
I don't understand: I agree that for a fixed value of m the function makes n recursive calls to itself, but when n reaches 1, n and m are decreased by 1 and the function will make n-1 recursive calls to itself, so the sum should be: (n-1)+(n-2)+...+1 which is O(n^2) for a fixed value of m, no?
yyy
No, when n reaches zero, the line "n=m-=1" has the effect "m=m-1; n=m;" which means the original value of n will not play any role in the subsequent computation
jpalecek
+1  A: 

Actually, it looks to be closer to O(N+m^2) to me. n is only used for the first "cycle".

Also, in any language that doesn't do tail call optimization the space complexity is likely to be "fails". In languages that support the optimization, the space complexity is more like O(1).

Darron