pow(x, n) using recursion
We can use the same approach as above but instead of an iterative loop, we can use recursion for the purpose.
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; int power( int x, int n) { // If x^0 return 1 if (n == 0) return 1; // If we need to find of 0^y if (x == 0) return 0; // For all other cases return x * power(x, n - 1); } // Driver Code int main() { int x = 2; int n = 3; // Function call cout << (power(x, n)); } // This code is contributed by Aditya Kumar (adityakumar129) |
Output
8
- Time Complexity: O(n)
- Auxiliary Space: O(n) n is the size of the recursion stack
C++ Program To Calculate the Power of a Number
Write a C++ program for a given two integers x and n, write a function to compute xn. We may assume that x and n are small and overflow doesn’t happen.
Examples :
Input : x = 2, n = 3
Output : 8Input : x = 7, n = 2
Output : 49
Contact Us