Created
March 15, 2018 03:56
-
-
Save Carleslc/79191adecc0fd849d144c2101c37f677 to your computer and use it in GitHub Desktop.
Factorial in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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