Power Using Recursion - GeeksforGeeks

Power Using Recursion

Last Updated : 6 Oct, 2026

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
redirect icon

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

file

Therefore, the output is 27.

C++
#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;
}
C
#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;
}
Java
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));
    }
}
Python
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))
C#
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));
    }
}
JavaScript
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.

Comment