102k views
4 votes
Write a recursive method named power that accepts two integers representing a base and an exponent and returns the base raised to that exponent. For example, the call of power(3, 4) should return 34 or 81 . If the exponent passed is negative, throw an IllegalArgumentException. Do not use loops or auxiliary data structures; solve the problem recursively. Also do not use the provided Java pow method in your solution.

1 Answer

6 votes

Answer:

The method in java is as follows:

public static int power(int num, int exp){

if(exp == 0){ return 1; }

if(exp < 0){

throw new IllegalArgumentException("Positive exponents only"); }

else{ return (num*power(num, exp-1)); }

}

Where


num\to base


exp \to exponent

Step-by-step explanation:

This defines the method

public static int power(int num, int exp){

This represents the base case, where the exponent is 0

if(exp == 0){

If yes, the function returns 1

return 1; }

If exponent is negative, this throws illegal argument exception

if(exp < 0){

throw new IllegalArgumentException("Positive exponents only"); }

If exponents is positive, this calls the function recursively

else{ return (num*power(num, exp-1)); }

}

User Joelazar
by
5.2k points