C program to find nth term of given recurrence relation



Suppose we have three numbers a, b, c and a value n. We follow a recurrence formula S(n) −

  • S(1) returns a
  • S(2) returns b
  • S(3) returns c
  • S(n) returns S(n-1) + S(n-2) + S(n-3) for all n > 3.

We shall have to find nth term by following this recurrence.

So, if the input is like a = 5, b = 2, c = 3, n = 6, then the output will be 28 because −

  • S(6) = S(5) + S(4) + S(3)
  • S(5) = S(4) + S(3) + S(2)
  • S(4) = S(3) + S(2) + S(1) = 3 + 2 + 5 = 10
  • so now S(5) = 10 + 3 + 2 = 15
  • and S(6) = 15 + 10 + 3 = 28

To solve this, we will follow these steps −

Define a function solve(), this will take a, b, c, n,

  • if n is same as 1, then:
    • return a
  • if n is same as 2, then:
    • return b
  • if n is same as 3, then:
    • return c
  • return solve((a, b, c, n - 1) + solve(a, b, c, n - 2) + solve(a, b, c, n - 3))

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
int solve(int a, int b, int c, int n){
    if(n == 1)
        return a;
    if(n == 2)
        return b;
    if(n == 3)
        return c;
    return solve(a, b, c, n-1) + solve(a, b, c, n-2) + solve(a, b, c, n-3);
}
int main(){
    int a = 5, b = 2, c = 3, n = 6;
    int res = solve(a, b, c, n);
    printf("%d", res);
}

Input

5, 2, 3, 6

Output

28

Advertisements