NPTEL Evaluating a Recurrence Relation

A recurrence relation T is defined on n >= 0 and is given as T(n) = T(n-1) + 2*n with the base case T(0) = 1. You will be given one integer k and you have to write a program to find out T(k). The program must implement T( ) recursively.


INPUT:
One integer k.

OUTPUT:
T(k)

CONSTRAINTS:
The input k will satisfy the constraints 0 <= k <= 1000. You do not have to check if the input given to you falls outside this range.

Solution:

#include<stdio.h>
 long long T(int input)
 {
 if(input == 0)
 return 1;

 return 2*input + T(input-1);
}
 int main()
{
 /*write your code here*/
 int k;
  scanf("%d",&k);
 printf("%lli",T(k));
 return 0;  
}

No comments:

Post a Comment

Share