Java program to calculate Power (x,n) using Recursion | Pow(x,n) with Example

The below logic will calculate the integer power of a number that is X^N where N is a integer. X ^ N is evaluated as X*X*X*….X up to N times that is X is multiplied by N times. This can be calculated by recursion, as recursion is a powerful mechanism which simplifies the logic too.

The algorithm for Power(double x, int n) will be as follows.

If n=0 , then the result is 1.0.

If n=1, then the result is the same as x.

If n>1, then the result is calculated by multiplying x by n times which can be calculated by recursion (x*Power(x,n-1))

if n<1, then n will be negative, that is x^-n which is equal to 1/x^n which can also be calculated by recursion (1.0 / Power(x, -n)); */

package net.javaonline;

class Power
 {
	public static void main(String args[])
	{
	if (args.length!=1) 
	  {
		System.out.println(&amp;quot;Input Error, Syntax : java Power  &amp;quot;x^n&amp;quot;  &amp;quot;);
		System.exit(0);
	}
	String strInput=args[0];
	int pos=strInput.indexOf('^' , 0);
	double x=0;
	int n=0;
	//to split the x and n from the input string 
	try
	{
		x=Double.parseDouble(strInput.substring(0,pos));
		n=Integer.parseInt(strInput.substring(pos+1));
	}
	catch (Exception e)
	 {
		 System.out.println(&amp;quot;Error, Syntax : java Power  &amp;quot;x^n&amp;quot;  where n is integer&amp;quot;);
		 System.exit(0);
	 }
		System.out.println();
		System.out.println(x+&amp;quot;^&amp;quot;+n+ &amp;quot; = &amp;quot;+ pow(x,n));
	}
	
	// Calculates the x raise to the power n 
	static double pow(double x, int n)
	{
		if (n==0 || n==1) return (n==0?1.0 : x);
		else if (n&amp;gt;1) return (x*pow(x,n-1));
		else return (1.0/pow(x,-n));
	}
}

Output

pow1 pow2 pow3 pow4

 

Try with  Live Demo

You may also like