-
Notifications
You must be signed in to change notification settings - Fork 109
/
Factorial.kt
45 lines (38 loc) · 997 Bytes
/
Factorial.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
45
package other
/**
*
* Algorithm for finding the factorial of a positive number n
*
*/
class Factorial {
/**
* iterative method
* worst time: O(n)
* amount of memory: O(1)
*/
fun compute(number: Int) : Int {
if (number <= 1) {
return 1
}
var result = 1
for (i in 2..number) {
result *= i
}
return result
}
/**
* recursive method
* worst time: O(n)
* amount of memory: O(n) - stack for recursion
*/
fun computeRecursive(number: Int) : Int {
return if (number <= 1) {
1
} else {
number * computeRecursive(number - 1)
}
}
// read more: https://kotlinlang.org/docs/functions.html#tail-recursive-functions
tailrec fun computeRecursiveWithKotlinOptimization(number: Int, result: Int = 1) : Int =
if (number <= 1) result else computeRecursiveWithKotlinOptimization(number - 1, result * number)
}