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
Selected Reading
C program to generate the value of x power n using recursive function
In C programming, calculating xn (x raised to the power n) can be efficiently done using recursive functions. This approach breaks down the problem into smaller subproblems, making the solution elegant and mathematically intuitive.
Syntax
long int power(int x, int n);
Algorithm
The recursive algorithm uses the following mathematical properties −
- If n = 1, then xn = x (base case)
- If n is even, then xn = (xn/2)2
- If n is odd, then xn = x × xn-1
Example: Recursive Power Function
Here's a complete C program that calculates xn using recursion −
#include <stdio.h>
#include <math.h>
long int power(int x, int n) {
if (n == 1)
return x;
else if (n % 2 == 0)
return pow(power(x, n/2), 2); /* if n is even */
else
return x * power(x, n-1); /* if n is odd */
}
int main() {
long int x, n, result;
printf("Enter the values of X and N:
");
scanf("%ld %ld", &x, &n);
result = power(x, n);
printf("X to the power N = %ld
", result);
return 0;
}
Enter the values of X and N: 5 4 X to the power N = 625
How It Works
For the input x=5, n=4, the recursive calls work as follows −
- power(5, 4): n is even, so calculate pow(power(5, 2), 2)
- power(5, 2): n is even, so calculate pow(power(5, 1), 2)
- power(5, 1): base case, returns 5
- Back to power(5, 2): returns pow(5, 2) = 25
- Back to power(5, 4): returns pow(25, 2) = 625
Key Points
- The algorithm has O(log n) time complexity due to the divide-and-conquer approach
- Using
pow()function requires#include <math.h> - The base case prevents infinite recursion
Conclusion
Recursive power calculation provides an efficient solution with logarithmic time complexity. The divide-and-conquer strategy significantly reduces the number of multiplications compared to iterative approaches.
Advertisements
