Last active
July 24, 2018 21:34
-
-
Save majidzeno/7361294d2eac863751c6d00b7db57349 to your computer and use it in GitHub Desktop.
Fibonnaci
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Fibonacci Function ( Recursion Case) (Very bad time complexity , very slow , the browser crash if you inter index of 50) | |
function fibonacci(position) { | |
if (position < 3) { | |
return 1; | |
} else { | |
return fibonacci(position - 1) + fibonacci(position - 2); | |
} | |
} | |
fibonacci(6); | |
------------------------------------------------------------------------------------------------------------------------------- | |
//Memoized Fibonnaci (Linear O(n) Time Complexity ) More effecient and fast | |
function fibMemo(index, cache) { | |
cache = cache || []; | |
//baseCase | |
if (cache[index]) { | |
return cache[index]; | |
} else { | |
if (index < 3) { | |
return 1; | |
} else { | |
cache[index] = fibMemo(index - 1, cache) + fibMemo(index - 2, cache); | |
} | |
} | |
return cache[index]; | |
} | |
fibMemo(1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment