Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big Oh Runtime of a Recursive Sum

If I use a for loop to find the sum of n numbers between 0 and n my runtime is O(n). But if I create a recursive function such as:

int sum(int n) {
    if(n == 0)
        return 0;
    return n + sum((n - 1));
}

Would my runtime still be O(n)?

like image 208
rctfan1999 Avatar asked Dec 14 '22 12:12

rctfan1999


2 Answers

Yes, your runtime will still be O(N). Your recursive function will "loop" N times until it hits the base case.

However keep in mind that your space complexity is also O(N). Your language has to save n + ... before evaluating sum((n - 1)), creating a stack of recursive calls that is N long.

like image 195
Primusa Avatar answered Dec 27 '22 00:12

Primusa


@Primusa's answer addresses your recursive runtime question. While my answer wont address your runtime question, it should be noted that you dont need an algorithm for this. The closed formula for the sum is (n+1)*(n) / 2.

thanks Carl Gauss!

like image 31
Bwebb Avatar answered Dec 27 '22 01:12

Bwebb