Created
June 28, 2018 04:36
-
-
Save johnteee/481e6c316f1f46f01ab97e511954057b to your computer and use it in GitHub Desktop.
fib.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
| function fibonacci(n) { | |
| return Math.round((Math.pow((1 + Math.sqrt(5)) / 2, n) - Math.pow(-2 / (1 + Math.sqrt(5)), n)) / Math.sqrt(5)); | |
| } | |
| function trampoline(f) { | |
| return function (...args){ | |
| var result = f( ...args ) | |
| while (typeof result === "function") { | |
| result = result() | |
| } | |
| return result | |
| } | |
| } | |
| function fib (n) { | |
| return trampoline(function inner_fib(n, a, b) { | |
| if (n === 0) {return a;} | |
| if (n === 1) {return b;} | |
| return () => inner_fib(n - 1, b, a + b); | |
| })(n, 0, 1); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment