Skip to content

Commit

Permalink
Add simple cache to speedup execution (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
102 authored Jun 12, 2024
1 parent 848e2c6 commit f06eb24
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
28 changes: 21 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,27 @@
* @returns {bigint}
*/
export function F(n, x, y) {
if (n === 0n) {
return x + y;
}
const cache = new Map();

if (y === 0n) {
return x;
}
return (function _F(_n, _x, _y) {
const cacheKey = [_n, _x, _y].join();

return F(n - 1n, F(n, x, y - 1n), F(n, x, y - 1n) + y);
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
}

if (_n === 0n) {
return _x + _y;
}

if (_y === 0n) {
return _x;
}

const result = _F(_n - 1n, _F(_n, _x, _y - 1n), _F(_n, _x, _y - 1n) + _y);

cache.set(cacheKey, result);

return result;
})(n, x, y);
}
2 changes: 2 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ let cases = [
[2n, 5n, 1n, 440n],
[2n, 1n, 2n, 10228n],
[2n, 2n, 2n, 15569256417n],
[2n, 3n, 2n, 5742397643169488579854258n],
[3n, 1n, 1n, 10228n],
];

cases.forEach(([n, x, y, expected]) => {
Expand Down

0 comments on commit f06eb24

Please sign in to comment.