Skip to content

Commit 7628541

Browse files
authored
Create FibonacciMemoization.kt
1 parent 513070d commit 7628541

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/kotlin/FibonacciMemoization.kt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Memoization dictionary to store computed Fibonacci numbers
2+
val memo = mutableMapOf<Int, Long>()
3+
4+
// Function to calculate Fibonacci numbers using memoization
5+
fun fibonacciMemoization(n: Int): Long {
6+
if (n <= 1) {
7+
return n.toLong()
8+
}
9+
10+
// Check if the result is already memoized
11+
if (memo.containsKey(n)) {
12+
return memo[n]!!
13+
}
14+
15+
// Calculate Fibonacci recursively and store the result in memoization
16+
val result = fibonacciMemoization(n - 1) + fibonacciMemoization(n - 2)
17+
memo[n] = result
18+
19+
return result
20+
}
21+
22+
fun main() {
23+
val index = 15
24+
println("Fibonacci (memoization) of $index is: ${fibonacciMemoization(index)}")
25+
}

0 commit comments

Comments
 (0)