DEV Community

Cover image for Day 9 of JavaScriptmas - Sum Odd Fibonacci Numbers Solution
Sekti Wicaksono
Sekti Wicaksono

Posted on

Day 9 of JavaScriptmas - Sum Odd Fibonacci Numbers Solution

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

Top comments (0)