1

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));
Philipp Wilhelm
  • 635
  • 1
  • 3
  • 16

2 Answers2

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)

Nenad
  • 119
  • 1
  • 11
1

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).

Philipp Wilhelm
  • 635
  • 1
  • 3
  • 16