0

Can anybody help me find time conplexity of this recursive function?

int test(int m, int n) {
    if(n == 0)
        return m;
    else
        return (3 + test(m + n, n - 1));
0

2 Answers 2

1

The test(m+n, n-1) is called n-1 times before base case which is if (n==0), so complexity is O(n)

Also, this is a duplicate of Determining complexity for recursive functions (Big O notation)

Sign up to request clarification or add additional context in comments.

Comments

0

It is really important to understand recursion and the time-complexity of recursive functions.

The first step to understand easy recursive functions like that is to be able to write the same function in an iterative way. This is not always easy and not always reasonable but in case of an easy function like yours this shouldn't be a problem.

So what happens in your function in every recursive call?

  • is n > 0?
  • If yes:
    • m = m + n + 3
    • n = n - 1
  • If no:
    • return m

Now it should be pretty easy to come up with the following (iterative) alternative:

int testIterative(int m, int n) {
    while(n != 0) {
        m = m + n + 3;
        n = n - 1;
    }
    return m;
}

Please note: You should pay attention to negative n. Do you understand what's the problem here?

Time complexity

After looking at the iterative version, it is easy to see that the time-complexity is depending on n: The time-complexity therefore is O(n).

2 Comments

correct but condition of While Loop should be : (n != 0). thanks :)
Just changed it. Thanks for the hint @MohammadFardin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.