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 lot of work, and looks less clean when you just want to use int
s (a power will then also always result in an int
).
Is there something as simple as a**b
like in Python?
If n is a positive integer and x is any real number, then xn corresponds to repeated multiplication xn=x×x×⋯×x⏟n times. We can call this “x raised to the power of n,” “x to the power of n,” or simply “x to the n.” Here, x is the base and n is the exponent or the power.
In Mathematic, the integers exponents are the exponents that should be an integer. It can be either a positive integer or a negative integer. In this, the positive integer exponents describe how many times the base number should be multiplied by itself.
Power is equal to work divided by time. In this example, P = 9000 J / 60 s = 150 W . You can also use our power calculator to find work – simply insert the values of power and time.
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.
When it's power of 2. Take in mind, that you can use simple and fast shift expression 1 << exponent
example:
22 = 1 << 2
= (int) Math.pow(2, 2)
210 = 1 << 10
= (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead
232 = 1L << 32
= (long) Math.pow(2, 32)
btw. in Kotlin you have shl
instead of <<
so
(java) 1L << 32
= 1L shl 32
(kotlin)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With