Skip to content

Instantly share code, notes, and snippets.

@Carleslc
Created March 15, 2018 03:56
Show Gist options
  • Save Carleslc/79191adecc0fd849d144c2101c37f677 to your computer and use it in GitHub Desktop.
Save Carleslc/79191adecc0fd849d144c2101c37f677 to your computer and use it in GitHub Desktop.
Factorial in Kotlin
/** If high-performance is needed consider using Guava BigIntegerMath.factorial instead **/
fun Long.factorial(): BigInteger {
fun factorial(start: Long, n: Long): BigInteger {
var i: Long
if (n <= 16) {
var r = BigInteger.valueOf(start)
i = start + 1
while (i < start + n) {
r = r.multiply(BigInteger.valueOf(i))
i++
}
return r
}
i = n / 2
return factorial(start, i) * factorial(start + i, n - i)
}
if (this <= 0) return BigInteger.ONE
return factorial(1, this)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment