neworldlt
12/08/2021, 5:25 PMJoffrey
12/08/2021, 7:36 PM1 shl n
Daniel
12/08/2021, 9:01 PMJoffrey
12/08/2021, 9:17 PM1 shl n // 2^n
than Math.pow(2.0, n.toDouble()).toInt()
Stephan Schroeder
12/09/2021, 7:49 AMfun twoPow(exponent: Int): Int {
require(exponent in 0..32) {"exponent must be in 0-31 but was $exponent"}
return 1 shl n // 2^n
}
val x = twoPow(5)
is hopefully even easier to read.
I didn't make it an extension function because i wanted to retain the order of 2 and 5.neworldlt
12/09/2021, 8:01 AMMath.pow()
can't guarantee the precision of what I need for bitwise operations. shl
does not look idiomatic either, because it is hard to read. I would say twoPow(x)
is winner here, however, it does not look idiomatic because it is not a part of stdlib, but maybe shouldI wonder why they did not build an extension for IntI guess it is because of precision. Double does not need that much of it.
Michael de Kaste
12/09/2021, 1:49 PMfun Int.pow(power: Int) = toBigInteger().pow(power)
powers can quite easily grow outside of the scope of an Int, so you have to decide what to do if your int gets out of range for its size. If you feel like you don't care, you can just do the .toInt() as part of it again.Joffrey
12/09/2021, 2:05 PM// 2^n
comment is a very short and clear way to explain the intent of it. But if it's not enough you can also extract it to a function like @Stephan Schroeder suggested. Also, incidentally (if it matters) I believe its performance will outweigh any other options in this case.
• If the base 2 was just incidental here and you're in fact using other bases in the same area of code, a custom extension for Int.pow(Int)
as @Michael de Kaste suggested would be my choice. The way you implement it is up to you (going through Double
or BigInteger
) but likely BigInteger
will be safer regarding overflows