Power of a given number using Recursion in Java

Power of a given number, x is a mathematical operation, written as  x^n. involving two numbers, the base x and the exponent  (or index or power)  n. When n is a positive number, exponentiation corresponds to repeated multiplication in other words, a product of n factors. For example, 5^4 = 5*5*5*5 =625

Power of a given number x raised to an exponent n is pow(x,n). Power function, pow(x,n) in Java implemented as native function using bit wise calculations of numbers for faster calculation.

Implementation in Math.java

public static double pow(double a, double b) {
  return StrictMath.pow(a, b); // default impl. delegates to StrictMath
}

StrictMath.java

public static native double pow(double a, double b);

Power function Recurrence relation or Algorithm is as below.

p(x,n)  = 1                        if(x=0)
        = x*p(x,n-1)               if(n>0)
        = (1/x)*p(x,n+1)           if(n<0)

 Pow(x,n) implementation in Java using Recursion

Here is the implementation for power of a given number using recursion in java

package com.jminded.recursion;

public class ComputePowerUsingRecursion {

	/**
	 * @author Umashankar
	 * {@link https://jminded.com}
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(computePower(2,5));
		System.out.println(computePower(2,-5));
		System.out.println(computePower(-2,5));
		System.out.println(computePower(-2,-5));

	}
	/**
	 * <p>Compute power</p>
	 * 
	 *  p(x,n)  =  1              if(x=0)
	 *          =  x*p(x,n-1)     if(n>0)
	 *          =  (1/x)*p(x,n+1) if(n<0)  
	 * @param x
	 * @param n
	 * @return
	 */
	public static double computePower(double x, double n){
		//base case
		if(n==0){
			return 1;
		}else if(n>0){   //recursive condition for postive power
			return x*computePower(x, n-1);
		}else if(n<0){  //recursive condition for negative power
			return (1/x)*computePower(x, n+1);
		}else{ 
			return -1;
		}
	}
}

 Output:

32.0
0.03125
-32.0
-0.03125

Leave a Comment