RosettaCodeData/Task/Factorial/Kotlin/factorial.kotlin

20 lines
466 B
Text
Raw Permalink Normal View History

2016-12-05 22:15:40 +01:00
fun facti(n: Int) = when {
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
2017-09-23 10:01:46 +02:00
else -> {
2016-12-05 22:15:40 +01:00
var ans = 1L
for (i in 2..n) ans *= i
ans
}
}
fun factr(n: Int): Long = when {
n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
n < 2 -> 1L
2017-09-23 10:01:46 +02:00
else -> n * factr(n - 1)
2016-12-05 22:15:40 +01:00
}
fun main(args: Array<String>) {
val n = 20
println("$n! = " + facti(n))
println("$n! = " + factr(n))
}