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).