Alex Rivera | Logout

Time complexity of a recursive algorithm

Asked 2010-04-25T17:15:11.077
29

How can I calculate the time complexity of a recursive algorithm?

int pow1(int x,int n) {
    if(n==0){
        return 1;
    }
    else{
        return x * pow1(x, n-1);
    }
}

int pow2(int x,int n) {
    if(n==0){
        return 1;
    }
    else if(n&1){
        int p = pow2(x, (n-1)/2)
        return x * p * p;
    }
    else {
        int p = pow2(x, n/2)
        return p * p;
    }
}
Edit
Report

1 Answer

12

Let's just start with pow1, because that's the simplest one.

You have a function where a single run is done in O(1). (Condition checking, returning, and multiplication are constant time.)

What you have left is then your recursion. What you need to do is analyze how often the function would end up calling itself. In pow1, it'll happen N times. N*O(1)=O(N).

For pow2, it's the same principle - a single run of the function runs in O(1). However, this time you're halving N every time. That means it will run log2(N) times - effectively once per bit. log2(N)*O(1)=O(log(N)).

Something which might help you is to exploit the fact that recursion can always be expressed as iteration (not always very simply, but it's possible. We can express pow1 as

result = 1;
while(n != 0)
{
  result = result*n;
  n = n - 1;
}

Now you have an iterative algorithm instead, and you might find it easier to analyze it that way.

answered 2010-04-25T17:28:56.223

Your Answer