Skip to content

Instantly share code, notes, and snippets.

@satyam4p
Created March 2, 2024 06:26
Show Gist options
  • Save satyam4p/5cc15f237edc4ece9565a96f512d8d30 to your computer and use it in GitHub Desktop.
Save satyam4p/5cc15f237edc4ece9565a96f512d8d30 to your computer and use it in GitHub Desktop.
Return sum of even numbers in fibonacci series which are even.
let cache = [];
function fib(num) {
if (cache[num] == undefined) {
if (num == 0) {
cache[0] = 0;
} else if (num == 1) {
cache[1] = 1;
} else {
cache[num] = fib(num - 1) + fib(num - 2);
}
}
return cache[num];
}
function cached(func) {
let cache = new Map();
return function (num) {
if (cache.has(num)) {
return cache.get(num);
} else {
let res = func(num);
cache.set(num, res);
return res;
}
};
}
let cachedFib = cached(fib);
function getEvenFib(num) {
let results = [];
for (let i = 0; i <= num; i++) {
let res = cachedFib(i);
if (res % 2 == 0) {
results.push(res);
}
}
return results.reduce((a, b) => a + b, 0);
}
console.log(getEvenFib(12));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment