Another Fib

by Lucille Kenney

HTML

<button id="sumFib" class="hwbutton">Get the Sum!</button>
<br>The sum of the first 50 even Fibonacci numbers is: <span class="" id="sumFibResult"></span>

JavaScript

var getFibSum = document.getElementById("sumFib");

getFibSum.onclick = function () {
    fiftyEvenFibonacciSum();
}

function fiftyEvenFibonacciSum() {
    var loopFib;
    //Initialize fibonacci array

    var fibonacci = new Array();

    //Add fibonacci array items
    fibonacci[0] = 0;
    fibonacci[1] = 1;
    var sum = 0;

    //Since it takes 150 fib numbers to obtain 50 even, loop through that many.
    for (loopFib = 2; loopFib <= 150; loopFib++) {

        // Next fibonacci number = previous + one before previous
        fibonacci[loopFib] = fibonacci[loopFib - 2] + fibonacci[loopFib - 1];

        //test for even numbers with if then statement
        var integer = parseInt(fibonacci[loopFib]);

        if (integer % 2 == 0) {

            //Add up the even fib numbers if even and output into dispay variable
            var display = sum += fibonacci[loopFib];

            //output results to html page
            document.getElementById("sumFibResult").innerHTML = display;

        }
    }
}