DEV Community

loading...
Cover image for Day 9 of JavaScriptmas - Sum Odd Fibonacci Numbers Solution

Day 9 of JavaScriptmas - Sum Odd Fibonacci Numbers Solution

Sekti
Keep moving forward. Learn well not learn fast.
・1 min read

Day 9 is calculate the sum odd fibonacci number.

For instance, the fibonacci number of 10 will has a sequence of number from 1 to 10: 1,1,2,3,5,8

But I want to calculate the odd number only: 1,1,3,5 the result will be 10.

This is the JavaScript solution

function sumOddFibonacciNumbers(num) {
     let limit = num,
        prev = 0, 
        current = 1, 
        next = 0, 
        totalOddNumber = 0;

    while(current <= limit) {
        next = prev + current;

        if(current % 2 === 1) {
            totalOddNumber += current;
        }

        prev = current;
        current = next;
    }

    return totalOddNumber;
}

Enter fullscreen mode Exit fullscreen mode

Discussion (0)