general.js > memonize.js > simple-loop.js
Created
January 29, 2018 15:00
-
-
Save kazu69/fa1f534f1586cba32643d12795dea85c to your computer and use it in GitHub Desktop.
Fibonacci algorithm in Javascript
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
const num = 20; | |
const fibonacci = (i) => { | |
const sqrt5 = Math.sqrt(5); | |
const phi = (sqrt5 + 1) / 2; | |
if (i < 2) { | |
return i; | |
} | |
return Math.round(Math.pow(phi, i) / sqrt5); | |
} | |
for (let i = 0; i < num; i++) { | |
const fib = fibonacci(i); | |
console.log(`result fib is ${fib}`); | |
} |
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
const num = 20; | |
const fibonacci = () => { | |
const memo = [0, 1]; | |
const fib = (i) => { | |
if (i < 0) { | |
return undefined; | |
} | |
if (typeof memo[i] === 'number') { | |
return memo[i]; | |
} | |
if (i < 2) { | |
memo[i] = i; | |
} else { | |
memo[i] = fibonacci1(i - 1) + fibonacci1(i - 2); | |
} | |
return memo[i]; | |
} | |
return fib; | |
} | |
for (let i = 0; i < num; i++) { | |
const fib = (fibonacci())(i); | |
console.log(`result fib is ${fib}`); | |
} |
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
const num = 20; | |
const fibonacci = (i) => { | |
return (i < 2 ? i : fibonacci1(i -1) + fibonacci1(i - 2)) | |
} | |
for (let i = 0; i < num; i++) { | |
const fib = fibonacci.call(null, i); | |
console.log(`result fib is ${fib}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment