4 Ways to Calculate Power of Number in Java

Here I have shared the 4 different ways to calculate power of number in Java.

  1. Using Loop
  2. Using Recursion
  3. Using Math.pow()
  4. Using BigInteger.pow()

4 Ways to Calculate Power of Number in Java

1. Using Loop

We can calculate the power of number by repeatedly multiplying the number by itself in a loop. This method works only for positive integer power.

package com;

import java.util.Scanner;

public class PowerOfNumber {
	public static void main(String args[]) {
		int n, p, result=1, i;
		Scanner sc = new Scanner(System.in);

		System.out.println("Enter a number and its power:");
		n = sc.nextInt();
		p =sc.nextInt();

		for(i = 1; i <= p; ++i){
			result = result * n;
		}
		
		System.out.println(result);
	}
}

 

Output

Enter a number and its power:
3
3
27

 

2. Using Recursion

Recursion can also be used to do this task. This method also works only for positive integer power.

package com;

import java.util.Scanner;

public class PowerOfNumber {
	public static void main(String args[]) {
		int n, p;
		Scanner sc = new Scanner(System.in);

		System.out.println("Enter a number and its power:");
		n = sc.nextInt();
		p =sc.nextInt();
		
		System.out.println(power(n, p));
	}
	
	public static int power(int n, int p){
		if(p == 1){
			return n;
		}
		
		return n * power(n, p - 1);
	}
}

 

3. Using Math.pow()

It is the simplest and very frequently used way. Math.pow() method takes tow double type arguments. First argument is the number and second is the power.

package com;

import java.util.Scanner;

public class PowerOfNumber {
	public static void main(String args[]) {
		int n, p;
		Scanner sc = new Scanner(System.in);

		System.out.println("Enter a number and its power:");
		n = sc.nextInt();
		p =sc.nextInt();
		
		System.out.println(Math.pow(n, p));
	}
}

 

4. Using BigInteger.pow()

BigInteger class provides method pow() to raise a number to a power. It can be used in following way.

import java.math.BigInteger;
import java.util.Scanner;

public class PowerOfNumber {
	public static void main(String args[]) {
		int n, p;
		Scanner sc = new Scanner(System.in);

		System.out.println("Enter a number and its power:");
		n = sc.nextInt();
		p =sc.nextInt();

		BigInteger bi = new BigInteger(n + "");
		System.out.println(bi.pow(p));
	}
}

 

Comment below if you know any other way to calculate power of number in java.

Leave a Comment

Your email address will not be published. Required fields are marked *