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.
function sumFibs(num) {
let first = 1
let second = 1;
let temp
let arr = [1]
while (second <= num) {
console.log(first, '-', second)
temp = first
first = second
second = temp + second
if (first % 2 === 1) {
arr.push(first)
}
console.log('after',first, '-', second)
}
return arr.reduce((x, y) => x + y);
}
console.log('res',
sumFibs(75025)
)
去除中间值和不使用reduce
function sumFibs(num) {
let prev = 1
let cur = 1;
let res = 1
while (cur <= num) {
console.log(prev, '-', cur)
cur = prev + cur
prev = cur - prev
if (prev % 2 === 1) {
res += prev
}
console.log('after', prev, '-', cur)
}
return res;
}
console.log('res',
sumFibs(75025)
)
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.
function sumFibs(num) {
let prevNumber = 0;
let currNumber = 1;
let result = 0;
while (currNumber <= num) {
if (currNumber % 2 !== 0) {
result += currNumber;
}
currNumber += prevNumber;
prevNumber = currNumber - prevNumber;
}
return result;
}
// test here
sumFibs(4);