-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathFactorialBigWithCache.kt
More file actions
42 lines (34 loc) · 849 Bytes
/
Copy pathFactorialBigWithCache.kt
File metadata and controls
42 lines (34 loc) · 849 Bytes
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
package other
import java.math.BigInteger
/**
*
* Algorithm for finding the factorial of a positive number n
*
* optimization: caching previous factorial values
*
* also adding large numbers
*
* worst time: O(n)
* the best time: O(1)
* amount of memory: O(n)
* problem: creating a huge number of BigInteger objects
*
*/
class FactorialBigWithCache {
private val cache = hashMapOf<Int, BigInteger>()
fun compute(number: Int) : BigInteger {
if (number <= 1) {
return BigInteger.ONE
}
val cachedResult = cache[number]
if (cachedResult != null) {
return cachedResult
}
var result = BigInteger.ONE
for (i in 2..number) {
result = result.multiply(i.toBigInteger())
cache[i] = result
}
return result
}
}