repl.it
@ashenm/

Sum All Odd Fibonacci Numbers

JavaScript

Specimen code solution for freeCodeCamp advanced algorithm scripting challenge.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * Sum All Odd Fibonacci Numbers
 * https://www.freecodecamp.org/challenges/sum-all-odd-fibonacci-numbers
 * Return the sum of all odd Fibonacci numbers that are less than or equal to a given positive integer
 *
 * Ashen Gunaratne
 * [email protected]
 *
 */

function sumFibs(num) {
  let current = 1;
  let adjacent = 1;
  let accumulate = current;
  while (adjacent <= num) {
    accumulate += (adjacent % 2 !== 0) ? adjacent : 0;
    adjacent += current;
    current = adjacent - current;
  }
  return accumulate;
}

// test here
sumFibs(4);
Native Browser JavaScript