Nir
12/09/2021, 5:46 PMephemient
12/09/2021, 6:24 PMNir
12/09/2021, 6:26 PMephemient
12/09/2021, 6:27 PMephemient
12/09/2021, 9:20 PMpow
is easy to write the naïve O(x) way,
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,
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
}
}
Nir
12/10/2021, 4:35 PMNir
12/10/2021, 4:36 PMshl
so you don't miss it as muchephemient
12/10/2021, 5:09 PM