File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -8,3 +8,29 @@ function fibonacci(position) {
8
8
// element at position(p) (p -1) and (p - 2)
9
9
return fibonacci ( position - 2 ) + fibonacci ( position - 1 ) ;
10
10
}
11
+
12
+ /**
13
+ * Memoization. In computing, memoization or memoisation is an
14
+ * optimization technique used primarily to speed up computer
15
+ * programs by storing the results of expensive function
16
+ * calls and returning the cached result when the
17
+ * same inputs occur again
18
+ */
19
+
20
+ // Linear time, test with index as 510 for both the functions
21
+ function fibonacciMemoized ( index , cache ) {
22
+ cache = cache || [ ] ;
23
+
24
+ if ( cache [ index ] ) {
25
+ return cache [ index ] ;
26
+ } else {
27
+ if ( index < 3 ) {
28
+ return 1 ;
29
+ } else {
30
+ cache [ index ] =
31
+ fibonacciMemoized ( index - 1 , cache ) +
32
+ fibonacciMemoized ( index - 2 , cache ) ;
33
+ }
34
+ }
35
+ return cache [ index ] ;
36
+ }
You can’t perform that action at this time.
0 commit comments