Recursive computation of number x raised to the power of n, $$ x^n$$ where $$ n \geq 0 $$
Power(X,N)
1 if N < 0 return Error(n>=0 is expected)
2 if N = 0 result = 1
3 else
4 if N > 0 result = X * Power(X,N-1)
We can raise a number to a power by repeatedly multiplying that number by itself. So if we know $$x^k$$ we can get $$ {x} ^ NaN$$ by multiplying $$x^k$$ by x. The recursive definition is $$x^k = x * x ^ NaN$$ This gives us the recursive case. The base case is $$ {x} ^ 0 $$ = 1 as any number raised to power 0 is 1.
JAVA IMPLEMENTATION
import java.util.Scanner;
/**
* Created by Ganesh.r.hegde on 16-Feb-18.
*/
public class RecursivePower {
public static void main(String[] args) {
System.out.println("Please enter the number :");
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
System.out.println("Please enter the positive exponent :");
int exp = scanner.nextInt();
if(exp < 0)
throw new IllegalArgumentException("Please enter positive exponent");
else
{
System.out.println(number + " to the power of "+exp +" is "+powers(number,exp));
}
}
/** Recursive power method
pre: n >= 0
@param x The number being raised to a power
@param n The exponent
@return x raised to the power n
*/
public static double powers(double x, int n) {
if (n == 0)
return 1;
else
return x * powers(x,n-1);
}
}