Time complexity of a recursive algorithm

前端 未结 5 2148
礼貌的吻别
礼貌的吻别 2020-11-29 01:19

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 *          


        
5条回答
  •  鱼传尺愫
    2020-11-29 02:14

    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.

提交回复
热议问题