Search code examples
javamethodsrecursionraise

Java Exponential Method


I need to write a method that will take a base and raises it to any integer power, positive or negative. It can be assumed that the base will not be 0.

In the method I need to call a recursive method and use it.

Here is the previous recursive method I need to use:

 public static double nonNegInt(double base, int pow)
{
    if (pow == 0)
    return 1;
    else
     return base * nonNegInt(base,pow-1);   
}

So my question is, can someone please help or show me how to write the method I need?

I know the current method is fine, but I need to call it in another method. When I do this I am getting a runtime error


Solution

  • Your method is a good start, although you will need to handle negative exponents as stated in your requirements. Take advantage of the fact that x^(-n) = 1.0 / x^n.