Thursday, September 10, 2015

Computing Powers Recursively in Java

Recursion can be applied to raise a number x to an arbitrary non-negative integer n.

If the input integer is a large integer value then BigInteger can be used in Java.

Simple method to calculate the power of an integer can be implemented as follows :


public class ComputingPowers {

 public static int power(int number, int exp)
 {
  if( exp == 0 )
   return 1;
  else
   return number*power(number, exp-1);
 }
 
 public static void main(String[] args) {
  
  System.out.println(power(2,6));
 }
 
}

This is one of the recursive solutions to calculate the power of an integer in Java.

There is a better algorithm which employs squaring technique. Advantage of using squaring technique is that it has got a better performance in terms of both time and space when compared to above implementation.

Squaring technique results in:

Time Complexity = O(logN)
Space Complexity = O(logN)

Reference :  http://www.amazon.com/Data-Structures-Algorithms-Java-Edition-ebook/dp/B00JDRQF8C


No comments:

Post a Comment