简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM