Created
March 2, 2024 06:26
-
-
Save satyam4p/5cc15f237edc4ece9565a96f512d8d30 to your computer and use it in GitHub Desktop.
Return sum of even numbers in fibonacci series which are even.
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
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