Recursive Function With Increasing Values

801 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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);
}
0
On

You will just need to maintain your loop variables and a counter, increasing the counter on each iteration until it equals the n, starting from n = 0 case (or 1, whatever).

Then when count == n you have your answer, so you end the loop.

Counting up instead of down is characteristic of corecursion, provided that each iteration step is finite (here, it certainly is).