emmcold / KoochiProblems

GNU General Public License v3.0
2 stars 1 forks source link

Print Cumulative Sum using recursion #18

Closed sinhaaman closed 6 years ago

sinhaaman commented 6 years ago

Print cumulative sum of the numbers starting from 1 to n.

e.g.

Input - n = 10;

Output: 1 3 6 10 15 21 28 36 45 55

Explanation : 1 3 (1 + 2) 6 (1 + 2 + 3) ... 55 (1 + 2+ 3 + 4 +5 +6 + 7 + 8 +9 +10)

Effectively the function becomes: F(n) = F(n-1) + n ; F(0) = 0;

Hint : 1 can also be treated as 0 + 1

emmcold commented 6 years ago

I did it :+1:

private static int printCumulativeSum(int n){
        if(n==0) return 0;
        int sum=printCumulativeSum(n-1)+n;
        System.out.println(sum);
        return sum;
    `}`
sinhaaman commented 6 years ago

Put this as a commit. Never provide code in the comment. This will lose tractability.

emmcold commented 6 years ago

Ok.

emmcold commented 6 years ago

I did this under the package 'otherProblems' and I didn't include it there because it looked more like a hanging problem....It doesn't belong to linked list or to trees, so I created this new package.