Is there a particular reason Kotlin doesn't have i...
# advent-of-code
n
Is there a particular reason Kotlin doesn't have integer exponentiation? Seems a bit odd to me tbh
e
unlike float and bigint, there's a very limited range of exponents before you don't fit into the integer datatype anymore
n
that is true, but when you want it, it's annoying not to have it
e
a modular integer exponentiation function could be more generally useful; python's stdlib pow does that, for example
if it helps,
pow
is easy to write the naïve O(x) way,
Copy code
fun Int.pow(x: Int): Int = (1..x).fold(1) { acc, _ -> acc * this }
and not too hard to write the faster O(log x) way,
Copy code
fun Int.pow(x: Int): Int = when {
    x < 0 -> throw ArithmeticException("negative exponent")
    x == 0 -> 1
    x == 1 || this == 0 || this == 1 -> this
    this == -1 -> if (x and 1 == 0) 1 else -1
    else -> {
        var r = 1
        var b = this
        var e = x
        while (true) {
            if (e and 1 != 0) r *= b
            e = e ushr 1
            if (e == 0) break
            b *= b
        }
        r
    }
}
n
I have to say this has come up a bunch of times now, there's been cases where we effectively have base 10 and base 5 numbers, so its just annoying not to have
with base 2 you happen to be able to use
shl
so you don't miss it as much
e
if this is for day 10 part 2, folding is better than exponentiating anyhow, as you don't need extra multiplications