Thursday, November 12, 2015

Power of a Number Implementation Recursive in Java

Calculation of exponentiation returns the value of the base number a raised to the exponent n.

Following is the recursive implementation of the power method in Java.


package basics;

public class PowerCalculator {

 public static long pow(long base, int n) {
  
  if (n == 0)
      return 1;
  
  if (n == 1)
      return base;
  
  if (n%2==0)
      return pow( base*base, n/2 );
  else
      return pow( base*base, n/2 )*base;
 }

 public static void main(String[] args) {
  
  long base = 2;
  int exponent = 4;
  System.out.println("Result of "+base+" to the "+exponent+" is = "+pow( base, exponent ));
  
  base = 3;
  exponent = 5;
  System.out.println("Result of "+base+" to the "+exponent+" is = "+pow( base, exponent ));
  
  base = 5;
  exponent = 4;
  System.out.println("Result of "+base+" to the "+exponent+" is = "+pow( base, exponent ));
  
 }
}



Create a PowerCalculator.java file in your workspace.

When the main method inside the PowerCalculator class executed it is going to print :

Result of 2 to the 4 is = 16
Result of 3 to the 5 is = 243
Result of 5 to the 4 is = 625


References :


Exponentiation in Wiki

Math pow method

Java 7 Math.pow implementation

For big numbers you can use Java-BigInteger

No comments:

Post a Comment