Given two numbers n and p, calculate n^p using recursion.
Examples:
Input: n = 9, p = 9
Output: 387420489
Explanation: 9 raised to the power 9 is 387420489.Input: n = 3, p = 3
Output: 27
Explanation: 3 raised to the power 3 is 27.
Try It Yourself
Recursive Multiplication - O(p) Time and O(p) Space
The idea is to calculate n^p recursively by multiplying n with the result of n^(p-1).
- If p == 0, return 1, since any number raised to the power 0 is 1.
- Otherwise, return n * power(n, p - 1).
- The recursion continues until the exponent becomes 0.
Consider n = 3 and p = 3

Therefore, the output is 27.
#include <iostream>
using namespace std;
int recursivePower(int n, int p)
{
if (p == 0)
return 1;
return n * recursivePower(n, p - 1);
}
int main()
{
int n = 3;
int p = 3;
cout << recursivePower(n, p);
return 0;
}
#include <stdio.h>
int recursivePower(int n, int p)
{
if (p == 0)
return 1;
return n * recursivePower(n, p - 1);
}
int main()
{
int n = 3;
int p = 3;
printf("%d", recursivePower(n, p));
return 0;
}
class GFG {
static int recursivePower(int n, int p)
{
if (p == 0)
return 1;
return n * recursivePower(n, p - 1);
}
public static void main(String[] args)
{
int n = 3;
int p = 3;
System.out.print(recursivePower(n, p));
}
}
def recursivePower(n, p):
if p == 0:
return 1
return n * recursivePower(n, p - 1)
if __name__ == "__main__":
n = 3
p = 3
print(recursivePower(n, p))
using System;
class GFG
{
static int recursivePower(int n, int p)
{
if (p == 0)
return 1;
return n * recursivePower(n, p - 1);
}
static void Main()
{
int n = 3;
int p = 3;
Console.Write(recursivePower(n, p));
}
}
function recursivePower(n, p) {
if (p === 0)
return 1;
return n * recursivePower(n, p - 1);
}
// Driver code
let n = 3;
let p = 3;
console.log(recursivePower(n, p));
Output
27
Please refer Power Function Implementation for more efficient approach.