Last active
April 22, 2017 19:33
-
-
Save rexfordkelly/d1e4eb98177166cf1bc46bb96832836d to your computer and use it in GitHub Desktop.
Examples of implementing iterative solutions for fib in js
This file contains hidden or 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
**Fib Explored.** | |
The following is based on some notes i've made while working through fib toy problems with others. | |
``` | |
/** | |
Simple iterative Fib sequence generator | |
*/ | |
function fib_seq(n){ | |
var i = 1; | |
var s = [1,1]; | |
while ( ++i <= n ){ // How many times will this loop run? Hint: n + 1 (for zero) - 2, or n - 1 times. | |
s[i] = s[ i-2 ] + s[ i-1 ]; | |
} | |
return (n < 0) ? undefined : s; // if n was less than 0, we return undefined, otherwise the full sequence we builtup. | |
} | |
/** | |
Simple iterative last Fib calculator | |
*/ | |
function last_fib( n ){ | |
var a,b,f,i; | |
a = 0, b = f = i = 1; | |
do { | |
f = (( a = b ) + ( b = f )); // Why does this work? hint: what do "()" mean in this expression. | |
} while( ++i < n ); | |
return n > 1 ? f : 1; | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment