Calculate the Power of a Number (n^p)

Posted by on Mar 31, 2024

Two numbers "n" and "p" are given, the task is to calculate and print Power (p) of a Number (n) i.e. n^p using recursion.

Example 1: Print 2 to the power of 8

Input: n=2, p=8
Output: 256

Example 2: Print 4 to the power of 3

Input: n=4, p=3
Output: 64


Solutions

Method 1: Recursion

We can solve this problem easily using recursion, all we need to do is multiplying current n to the result of f(n, p-1) and break the recursion when p==0 (Base Condition).

package com.cb.recursion;

public class R7_PowerOfANumber {
    public static int pow(int n, int p) {
        if (p == 0)
            return 1;
        return n * pow(n, p - 1);
    }

    public static void main(String[] args) {
        System.out.println(pow(2,8));
        System.out.println(pow(4,3));
    }
}
256
64

Complexity
The time complexity of this solution is O(p) and space complexity is O(1).

Related


Check if an integer array is sorted or not

Program for printing nth Fibonacci Number

Print spelling for a given number

Print numbers from a given number to 0

Count ways to reach the nth stair

Sum of the digits of a given number

Write a program to reverse a string

Print numbers from 0 to a given number

Calculate factorial of a given number

Program to solve "Tower of Hanoi" problem