So you start with a value for num
- say 10.
Fibonacci sequence adds the previous two numbers in the sequence together - 0 + 1 is 1, 1 + 1 is 2, 1 + 2 is 3, 2 + 3 is 5 and so on.
So the fib
array starts at [1, 1]: it’s always an array with at least two elements, and those two elements have to be the start of the sequence (can be 0 and 1, makes no difference to the end result).
The loop starts with a counter i
at 0. It’s going to stop when num - fib[i + 1]
is > fib[i]
: ie when the target number minus the last element in the array is greater than the second-last element in the array.
The aim of the loop is to add a value to fib
on each iteration, and it’s going to move through the the array and look at the value behind that.
So num
is 10, fib
is [1,1]
, i
is 0
fib[i] <= num - fib[i + 1]
1 <= 10 - 1
true
// so
fib.push(fib[i] + fib[i + 1])
fib.push(1 + 1)
fib.push(2)
So num
is 10, fib
is [1,1,2]
, i
is 1
fib[i] <= num - fib[i + 1]
1 <= 10 - 2
true
// so
fib.push(fib[i] + fib[i + 1])
fib.push(1 + 2)
fib.push(3)
So num
is 10, fib
is [1,1,2,3]
, i
is 2
fib[i] <= num - fib[i + 1]
2 <= 10 - 3
true
// so
fib.push(fib[i] + fib[i + 1])
fib.push(2 + 3)
fib.push(5)
So num
is 10, fib
is [1,1,2,3,5]
, i
is 3
fib[i] <= num - fib[i + 1]
3 <= 10 - 5
true
// so
fib.push(fib[i] + fib[i + 1])
fib.push(3 + 5)
fib.push(8)
So num
is 10, fib
is [1,1,2,3,5,8]
, i
is 4
fib[i] <= num - fib[i + 1]
5 <= 10 - 8
false
// loop ends
fib
is now [1,1,2,3,5,8]
. Filter that for odd numbers, then sum.