Search code examples
algorithmrecursioniterationcorecursion

Recursive Function With Increasing Values


I am trying to write a recursive function the evaluate for n

3(2+1)+4(3+2+1)+...+(n+1)(n+...+2+1)

I know that in general we need to write it as induction the result for the base case let say n=1 and then call the function for n-1 which will end up in the base case.

But in the following function the elements increases, how should I approach this


Solution

  • This is also the same as the general way you mentioned. just look at it this way:

    (n+1)(n + (n-1) + (n-2) + ... + 1) + (n)((n-1) + (n-2) + ... + 1) + (n-1)((n-2) + (n-3) + ... + 1)

    so assume you have a function named SumTo(n), which return sum of all numbers starting at 1 up to n, this is the recursive function :

    int Calc(n)
    {
       if (n == 3)
         return n(sumTo(2));
    
       else return n(sumTo(n-1)) * Calc(n-1);
    }