Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit dbd3dbd

Browse files
committed
--update: added optimized fibonacci using cache
1 parent c2eec66 commit dbd3dbd

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

‎src/_Classics_/fibonacci/index.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,29 @@ function fibonacci(position) {
88
// element at position(p) (p -1) and (p - 2)
99
return fibonacci(position - 2) + fibonacci(position - 1);
1010
}
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /