Java Program – Compute x^n By Recursion

This program computes the power of a number by recursion. That is it calculates x^n (x raised to teh power n) for a positive integer n and a positive integer x.

/* Power of a number by recursion
Write a recursive mathematical definition for computing x^n for a positive integer n
and a positive integer x.
E.g. Computer x ^ n by recursion
Mukesh Tekwani
*/

import java.util.Scanner;

class PowerofN
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);

		System.out.print("Enter the number x:");
		int x = input.nextInt();		

		System.out.print("Enter the power of x:");
		int n = input.nextInt();		

		//take care of mischief by user
		if (x < 0)
			x = -x;

		if (n < 0)
			n = -n;

		System.out.println(x + " raised to " + n + " is " + power(x, n));
	}


	public static long power(int x, int n)
	{
		if (n == 0)  //base case
			return 1;
		else if (n == 1)
			return x;
		else 
			return (x * power(x, n - 1));
	}
}
%d bloggers like this: