Last active
January 6, 2020 08:07
-
-
Save Iainmon/527806b4117032abb36f4064de04c957 to your computer and use it in GitHub Desktop.
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
| /// <reference path="../node_modules/assemblyscript/index.d.ts" /> | |
| declare type u64 = number; | |
| // It’s time for constant time complexity! | |
| var memory = new Map<u64, u64>(); | |
| // Fibonacci wrapper for memory | |
| export function fib(n: u64): u64 { | |
| // Checks if the pair is memorized | |
| if (memory.has(n)) { | |
| return memory.get(n); | |
| } | |
| // Saves the value to memory | |
| memory.set(n, _fib(n)); | |
| // Returns the saved value | |
| return memory.get(n); | |
| } | |
| // Recursive Fibonacci function | |
| function _fib(n: u64): u64 { | |
| if (n <= 1) { | |
| return n; | |
| } | |
| return _fib(n - 1) + _fib(n - 2); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment