Profile Photo

calculate-powxn

Created on: Jan 20, 2025

Given two integers x and n, write a function to compute xn. We may assume that x and n are small and overflow doesn’t happen. We can't use Math library.

Input : x = 2, n = 3 Output : 8 Input : x = 7, n = 2 Output : 49
public class Solution { public static double power(double base, int exp) { return 0.0 } public static void main(String[] args) { boolean testsPass = true; double result = power(2,-2); // System.out.println(result); // testsPass = testsPass && result == 59049.0; testsPass = testsPass && power(2,-2) == 0.25; testsPass = testsPass && power(2,2) == 4; testsPass = testsPass && power(3,10) == 59049.0; if (testsPass) { System.out.println("Pass"); } else { System.out.println("There are failures"); } } }

Recursive approach

public static double power(double base, int exp) { if (exp == 0) return 1; if (exp < 1) return 1 / power(base, -exp); if (exp % 2 == 1) { return base * power(base * base, (exp - 1) / 2); } else { return power(base * base, (exp) / 2); } }
Time complexity: Log(n)