Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating powers of integers

Tags:

java

math

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 ints (a power will then also always result in an int).

Is there something as simple as a**b like in Python?

like image 761
Hidde Avatar asked Nov 09 '11 20:11

Hidde


People also ask

How do you find the power of an integer?

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.

What are powers of integers?

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.

How do I calculate power?

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.


2 Answers

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.

like image 168
JB Nizet Avatar answered Oct 06 '22 00:10

JB Nizet


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)

like image 21
Stanislaw Baranski Avatar answered Oct 06 '22 00:10

Stanislaw Baranski