We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 513070d commit 7628541Copy full SHA for 7628541
src/kotlin/FibonacciMemoization.kt
@@ -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