Calculate Power Using Recursion

Calculate Power Using Recursion

Medium C++ Functions 37 views
Explanation Complexity

Problem Statement

Calculate x raised to power n (x^n) using recursive function.
Real Life: Like calculating compound interest repeatedly.

Input Format

Two integers:

• x (base)

• n (power)

Output Format

Value of x^n.

Example

2 5 
32

Constraints

• n ≥ 0

• Use recursion

• Result fits in data type

Concept Explanation

x^n means multiplying x by itself n times.
Recursion solves this by reducing the power step by step.
This is similar to compound interest, where the same operation repeats.

Step-by-Step Explanation

1.Define a recursive function power(x, n).

2.Base case:

• If n == 0, return 1.

3.Recursive case:

• Return x * power(x, n - 1).

4.Each call reduces n by 1.

5.Calls stop when n becomes 0.

6.Final value is returned to main() and printed.

Concept Explanation

x^n means multiplying x by itself n times.
Recursion solves this by reducing the power step by step.
This is similar to compound interest, where the same operation repeats.

Step-by-Step Explanation

1.Define a recursive function power(x, n).

2.Base case:

• If n == 0, return 1.

3.Recursive case:

• Return x * power(x, n - 1).

4.Each call reduces n by 1.

5.Calls stop when n becomes 0.

6.Final value is returned to main() and printed.

Input / Output Format

Input Format
Two integers:

• x (base)

• n (power)
Output Format
Value of x^n.
Constraints
• n ≥ 0

• Use recursion

• Result fits in data type

Examples

Input:
2 5
Output:
32

Example Solution (Public)

C++
int calculatePower(int base, int exponent) {
    if(exponent == 0) {
        return 1;  // Base case
    }
    return base * calculatePower(base, exponent - 1);  // Recursive call
}

void function_q6_power_recursion() {
    int x = 2;
    int n = 5;
    
    int result = calculatePower(x, n);
    cout << x << " raised to power " << n << " is: " << result << endl;
}

Official Solution Code

int calculatePower(int base, int exponent) {
    if(exponent == 0) {
        return 1;  // Base case
    }
    return base * calculatePower(base, exponent - 1);  // Recursive call
}

void function_q6_power_recursion() {
    int x = 2;
    int n = 5;
    
    int result = calculatePower(x, n);
    cout << x << " raised to power " << n << " is: " << result << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.