Calculate power of a number in Java

Java Program to Calculate the power of a number

The power of a number in java is used to calculate the value for the first integer value raised to the value of the second integer. There are some points we have to be careful about while using the pow() function.

  • If the second integer is 0, the output will be always 1.
  • When the value of the second integer is 1, the output will always be the first integer.
  • If the second integer is NaN, the output will also be NaN.

Different Ways to calculate the power of a number

  1. We can calculate power with the help of a while loop.
  2. By using for loop.
  3. By using pow() function.

For better understanding, let’s see how we can calculate power using a while loop.

public class DeveloperHelps {
public static void main(String[] args) {
int base = 5, exponent = -4;
long output = 1;
while (exponent != 0) {
output *= base;
--exponent;
}
System.out.println("The power is = " + output);
}
}

The output of the program will be:

The power is = -7659036730666025327

Let’s try a program using for loop in Java now

public class JavaExample {
public static void main(String[] args) {
int number = 2, p = 5;
long result = 1;
int i = p;
for (;i != 0; --i) {
result *= number;
}
System.out.println("The power is = "+result);
}
}

The output of the above program is:

The power is = 32

Below is a program to understand how we can calculate power of a number using pow() function.

public class DeveloperHelps {
public static void main(String[] args) {
int base = 5, exponent = -4;
double result = Math.pow(base, exponent);
System.out.println("The power is = " + result);
}
}

The output of the program will be:

The power is = 0.0016

This is the most optimized code in java with the least complexity. The pow() function is found under java.lang.Math is directly used to calculate the power of a number. The pow() function will directly take two numbers as integers and returns the output as the first integer value raised to the value of the second integer.

Thanks for the reading post. I hope you like and understand the post. If you have any doubts regarding this post please comment below.

Leave a comment

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