My Question
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.
My Answer
function sumFibs(num, total = [1, 1]) {
const n = total[total.length - 1] + total[total.length - 2];
if(n > num){
return total;
}
if(n %2 ==0){
total.push(n);
}
return sumFibs(num, total);
}
sumFibs(4);
The Problem
It keeps saying maximum call stack exceeded. I am pretty sure it is because of the second if statement. Any idea how I can fix this?
I even tried this:
function sumFibs(num, total = [1, 1]) {
const n = total[total.length - 1] + total[total.length - 2];
if(n > num){
return total;
}
let x = Array.from(n);
let y = x.filter((item)=>{
return item % 2== 0
})
total.push(...y)
return sumFibs(num, total);
}
sumFibs(4);