Intermediate Algorithm Scripting - Sum All Odd Fibonacci Numbers

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]))
    { 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)


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

Link to the challenge:

Havent included 0 in the array because its not needed for the sum

btw reduce is so helpful thats crazy

function sumFibs(num) {
  const fibs = [];
  for (let i = 0; i <= num; i++) {
    if (i >= 2) {
      fibs.push(fibs[i-2] + fibs[i-1]);
    } else {
  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.

Good work getting a solution!

1 Like

Hello Jeremy and Ikh.

Dear Jeremy, I tried modifying per your suggestion. I think I did everything except not using array. Maybe will figure later =)

  const fibs = [0,1];
  for (let i = 2; fibs[i-1] <= num; i++) {
      fibs.push(fibs[i-2] + fibs[i-1]);
  return fibs
    .filter((x) => x % 2 && x <= num)
    .reduce((sum, x) => sum += x);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.