Power using Recursion
Calculate Power using Recursion in C++
IntermediateTopic: Recursion Programs
C++ Power using Recursion Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
// Recursive function to calculate power
double power(double base, int exponent) {
// Base cases
if (exponent == 0) {
return 1;
}
if (exponent == 1) {
return base;
}
// Handle negative exponent
if (exponent < 0) {
return 1.0 / power(base, -exponent);
}
// Optimized: Divide and conquer
// If exponent is even: base^exp = (base^(exp/2))^2
// If exponent is odd: base^exp = base * (base^(exp/2))^2
if (exponent % 2 == 0) {
double half = power(base, exponent / 2);
return half * half;
} else {
double half = power(base, (exponent - 1) / 2);
return base * half * half;
}
}
int main() {
double base;
int exponent;
cout << "Enter base: ";
cin >> base;
cout << "Enter exponent: ";
cin >> exponent;
double result = power(base, exponent);
cout << base << "^" << exponent << " = " << result << endl;
// Test various powers
cout << "\nVarious powers:" << endl;
cout << "2^10 = " << power(2, 10) << endl;
cout << "3^5 = " << power(3, 5) << endl;
cout << "5^-2 = " << power(5, -2) << endl;
cout << "10^0 = " << power(10, 0) << endl;
return 0;
}Output
Enter base: 2 Enter exponent: 8 2^8 = 256 Various powers: 2^10 = 1024 3^5 = 243 5^-2 = 0.04 10^0 = 1
Understanding Power using Recursion
Power calculation using recursion with optimization. For even exponent: base^exp = (base^(exp/2))^2. For odd exponent: base^exp = base * (base^((exp-1)/2))^2. Time complexity: O(log n) instead of O(n). Handles negative exponents by returning 1/base^|exp|. Divide-and-conquer approach reduces recursive calls.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.