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 0 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first seven numbers of the Fibonacci sequence are 0, 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.
I submitted the following code which did not pass all the tests:
function sumFibs(num){
const fibonaciArr = [0,1];
let add = 0;
for(let i = 0; i < num; i++){
if(fibonaciArr[i+1]%2 !== 0) add+=fibonaciArr[i+1];
fibonaciArr.push(fibonaciArr[i] + fibonaciArr[i + 1])
}
return add;
}
I used the fibonaciArr to come up with the sequence just to see whether the sequence is ok.
3
Answers
The Fibonacci numbers grow pretty fast. Using your code,
sumFibs(76)
is the last value that can be represented exactly in JavaScript or in any other language that uses the double-precision 64-bit binary format IEEE 754 to represent the real numbers. This format can represent exactly the integer numbers in the interval -253 + 1 to 253 – 1. JavaScript provides the constantsNumber.MIN_SAFE_INTEGER
andNumber.MAX_SAFE_INTEGER
for these values.The values outside this interval are rounded to the nearest multiple of a power of 2. The values between 253 and 254 – 1 are rounded to the next multiple of 2, the values between 254 and 255 – 1 are rounded to the next multiple of 4 and so on.
This means that the 77th and the subsequent Fibonacci numbers cannot be computed. They are rounded to even numbers and your code ignores the even numbers.
You can solve this by using
BigInt
numbers.Check it online.
Read about how JavaScript works with numbers.
Axiac’s answer perfectly addressed the problem. I just add that you can easily solve this problem in JavaScript by using BigInt numbers in place of plain numbers.
In order to do so, you have to place a
n
after every your number literal:As mentioned the Fibonacci sequence can get big pretty fast,.
But since we are dealing in integers, you can convert your code into using
BigInt
.Below is an example.