Skip to content

Instantly share code, notes, and snippets.

@Iainmon
Last active January 6, 2020 08:07
Show Gist options
  • Select an option

  • Save Iainmon/527806b4117032abb36f4064de04c957 to your computer and use it in GitHub Desktop.

Select an option

Save Iainmon/527806b4117032abb36f4064de04c957 to your computer and use it in GitHub Desktop.
/// <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