Tell us what’s happening:
Came up with my own solution for the sum of odd fibonacci numbers! Please let me know if there was an easier solution, or if my code can be shortened! Thanks
Your code so far
function sumFibs(num) {
let x = []
/* creating a fibonacci array without the 0
( also its not really fibonacci because the lenght of the array
is equal to the num and i fix it in the last step) */
for ( let i = 0; i <= num;i++)
{if (i >=2 ) {
x.push( (x[i-2] + x[i-1]))
}
else
{ x.push(i)}
}
/* use filter to filter the odd numbers
and reduce to sum up the array */
return x.filter((x) => x% 2 && x <= num)
.reduce((sum,x) => sum += x)
}
console.log(sumFibs(75025));
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15
Challenge: Intermediate Algorithm Scripting - Sum All Odd Fibonacci Numbers
function sumFibs(num) {
const fibs = [];
for (let i = 0; i <= num; i++) {
if (i >= 2) {
fibs.push(fibs[i-2] + fibs[i-1]);
} else {
fibs.push(i);
}
}
return fibs
.filter((x) => x % 2 && x <= num)
.reduce((sum, x) => sum += x);
}
I applied some formatting fixes. Using consistent formatting and clear variable names is important.
You can remove the conditional expression if you start the array with the first two Fibonacci numbers. The if statement inside of the loop slows it down a fair amount and you don’t really need it if you change the initial array.
Also, you are computing way, way more Fibonacci numbers than you need by using a for loop with those bounds. You want all fibs less than num, not the first numth fibs!
The most efficient approach is to actually not use an array at all. Some of the solutions in the guide take that approach.