Is there any other way in Java to calculate a power of an integer?
I use Math.pow(a, b)
now, but it returns a double
, and that is usually a
Guava's math libraries offer two methods that are useful when calculating exact integer powers:
pow(int b, int k) calculates b to the kth the power, and wraps on overflow
checkedPow(int b, int k) is identical except that it throws ArithmeticException
on overflow
Personally checkedPow()
meets most of my needs for integer exponentiation and is cleaner and safter than using the double versions and rounding, etc. In almost all the places I want a power function, overflow is an error (or impossible, but I want to be told if the impossible ever becomes possible).
If you want get a long
result, you can just use the corresponding LongMath methods and pass int
arguments.
Use the below logic to calculate the n power of a.
Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n) Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).
public int calculatePower1(int a, int b) {
if (b == 0) {
return 1;
}
int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;
int temp = 1;
for (int i = 1; i <= val; i++) {
temp *= a;
}
if (b % 2 == 0) {
return temp * temp;
} else {
return a * temp * temp;
}
}
No, there is not something as short as a**b
Here is a simple loop, if you want to avoid doubles:
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
If you want to use pow
and convert the result in to integer, cast the result as follows:
int result = (int)Math.pow(a, b);
Integers are only 32 bits. This means that its max value is 2^31 -1
. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow
uses double
.
If you want arbitrary integer precision, use BigInteger.pow. But it's of course less efficient.
Well you can simply use Math.pow(a,b)
as you have used earlier and just convert its value by using (int)
before it. Below could be used as an example to it.
int x = (int) Math.pow(a,b);
where a
and b
could be double
or int
values as you want.
This will simply convert its output to an integer value as you required.
import java.util.*;
public class Power {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int num = 0;
int pow = 0;
int power = 0;
System.out.print("Enter number: ");
num = sc.nextInt();
System.out.print("Enter power: ");
pow = sc.nextInt();
System.out.print(power(num,pow));
}
public static int power(int a, int b)
{
int power = 1;
for(int c = 0; c < b; c++)
power *= a;
return power;
}
}