Skip to content

Instantly share code, notes, and snippets.

@cesartl
Created May 9, 2020 08:12
Show Gist options
  • Save cesartl/7d258138069c85d2cd5bb22780ad8853 to your computer and use it in GitHub Desktop.
Save cesartl/7d258138069c85d2cd5bb22780ad8853 to your computer and use it in GitHub Desktop.
/**
* Exponentiation by squaring
* https://en.wikipedia.org/wiki/Exponentiation_by_squaring
*/
fun <T> Monoid<T>.combineTimes(m: T, k: BigInteger): T {
if (k == BigInteger.ZERO) {
return empty()
}
if (k == BigInteger.ONE) {
return m
}
var y = empty()
var x = m
var n = k
while (n > BigInteger.ONE) {
if (n.testBit(0)) {
// n is odd
y = y.combine(x)
x = x.combine(x)
n -= BigInteger.ONE
} else {
// n is even
x = x.combine(x)
}
n /= BigInteger.TWO
}
return x.combine(y)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment