https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers

Sum All Odd Fibonacci Numbers

Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.

The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.

For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.

sumFibs(1) should return a number.

Passed

sumFibs(1000) should return 1785.

Passed

sumFibs(4000000) should return 4613732.

Passed

sumFibs(4) should return 5.

Passed

sumFibs(75024) should return 60696.

Passed

sumFibs(75025) should return 135721.

  1. function sumFibs(num) {
  2. let first = 1
  3. let second = 1;
  4. let temp
  5. let arr = [1]
  6. while (second <= num) {
  7. console.log(first, '-', second)
  8. temp = first
  9. first = second
  10. second = temp + second
  11. if (first % 2 === 1) {
  12. arr.push(first)
  13. }
  14. console.log('after',first, '-', second)
  15. }
  16. return arr.reduce((x, y) => x + y);
  17. }
  18. console.log('res',
  19. sumFibs(75025)
  20. )

去除中间值和不使用reduce

  1. function sumFibs(num) {
  2. let prev = 1
  3. let cur = 1;
  4. let res = 1
  5. while (cur <= num) {
  6. console.log(prev, '-', cur)
  7. cur = prev + cur
  8. prev = cur - prev
  9. if (prev % 2 === 1) {
  10. res += prev
  11. }
  12. console.log('after', prev, '-', cur)
  13. }
  14. return res;
  15. }
  16. console.log('res',
  17. sumFibs(75025)
  18. )

Problem Explanation

You will need to gather all the Fibonacci numbers and then check for the odd ones. Once you get the odd ones then you will add them all. The last number should be the number given as a parameter if it actually happens to be an off Fibonacci number.

  1. function sumFibs(num) {
  2. let prevNumber = 0;
  3. let currNumber = 1;
  4. let result = 0;
  5. while (currNumber <= num) {
  6. if (currNumber % 2 !== 0) {
  7. result += currNumber;
  8. }
  9. currNumber += prevNumber;
  10. prevNumber = currNumber - prevNumber;
  11. }
  12. return result;
  13. }
  14. // test here
  15. sumFibs(4);