forked from igorwojda/kotlin-coding-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.kt
44 lines (38 loc) · 924 Bytes
/
solution.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.igorwojda.integer.factorial
// iterative solution
private object Solution1 {
private fun factorial(n: Int): Int {
var total = 1
(1..n).forEach {
total *= it
}
return total
}
}
// another iterative solution
private object Solution2 {
private fun factorial(n: Int): Int =
when (n) {
0 -> 1
else -> (n downTo 1).reduce { acc, it -> acc * it }
}
}
// recursive solution
private object Solution3 {
private fun factorial(n: Int): Int =
when (n) {
0, 1 -> 1
else -> n * factorial(n - 1)
}
}
// Tail-recursive solution
private object Solution4 {
private fun factorial(n: Int): Int {
fun fact(n: Int, acc: Int = 1): Int =
when (n) {
0, 1 -> acc
else -> fact(n - 1, acc * n)
}
return fact(n)
}
}