Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to find nth term of given recurrence relation
In C programming, we can find the nth term of a given recurrence relation where each term is the sum of the previous three terms. This type of recurrence relation follows the pattern S(n) = S(n-1) + S(n-2) + S(n-3) for n > 3, with given base cases.
Syntax
int solve(int a, int b, int c, int n);
Recurrence Relation Definition
The recurrence relation is defined as follows −
- S(1) = a (first base case)
- S(2) = b (second base case)
- S(3) = c (third base case)
- S(n) = S(n-1) + S(n-2) + S(n-3) for all n > 3
Example: Using Recursive Approach
This example demonstrates finding the 6th term where a = 5, b = 2, c = 3 −
#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 result = solve(a, b, c, n);
printf("The %dth term is: %d<br>", n, result);
return 0;
}
The 6th term is: 28
How It Works
The calculation proceeds as follows −
- S(4) = S(3) + S(2) + S(1) = 3 + 2 + 5 = 10
- S(5) = S(4) + S(3) + S(2) = 10 + 3 + 2 = 15
- S(6) = S(5) + S(4) + S(3) = 15 + 10 + 3 = 28
Example: Optimized Dynamic Programming Approach
For better performance with larger values of n, we can use an iterative approach −
#include <stdio.h>
int solveOptimized(int a, int b, int c, int n) {
if (n == 1) return a;
if (n == 2) return b;
if (n == 3) return c;
int first = a, second = b, third = c;
int result;
for (int i = 4; i <= n; i++) {
result = first + second + third;
first = second;
second = third;
third = result;
}
return result;
}
int main() {
int a = 5, b = 2, c = 3, n = 6;
int result = solveOptimized(a, b, c, n);
printf("The %dth term (optimized): %d<br>", n, result);
return 0;
}
The 6th term (optimized): 28
Key Points
- The recursive approach has exponential time complexity O(3^n) due to repeated calculations.
- The iterative approach has linear time complexity O(n) and constant space complexity.
- For large values of n, always prefer the iterative approach to avoid stack overflow.
Conclusion
Recurrence relations can be solved using either recursive or iterative approaches. While recursion is more intuitive, the optimized iterative solution provides better performance for larger inputs by avoiding redundant calculations.
