How to find the sum of the even valued in fibonacci sequence with JavaScript

2 Answers

0 votes
function sumEvenNumbersInFibonacci(n) {
    if (n < 1) {
        return 0;
    }

    let currentNumber = 0;
    let nextNumber = 1;
    let sum = 0;
    let s = "0 1";

    for (let i = 0; i < n - 2; i++) {
        let temp = nextNumber;
        nextNumber = currentNumber + nextNumber;
        currentNumber = temp;
        s += " " + nextNumber;

        if (nextNumber % 2 === 0) {
            sum += nextNumber;
        }
    }
    console.log(s)
    

    return sum;
}


let limit = 15;

let sumResult = sumEvenNumbersInFibonacci(limit);

console.log("Sum = " + sumResult);

  
  
/*
run:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Sum = 188

*/

 



answered Apr 16, 2025 by avibootz
edited Apr 16, 2025 by avibootz
0 votes
function sumEvenFibonacci(limit) {
    let a = 1, b = 2; // Starting Fibonacci numbers
    let sum = 0;

    while (a <= limit) {
        if (a % 2 === 0) {
            sum += a; // Add to sum if the number is even
        }
        [a, b] = [b, a + b]; // Generate the next Fibonacci number
    }

    return sum;
}

const limit = 4000000; 

console.log(sumEvenFibonacci(limit)); 


 
/*
run:
     
4613732
      
*/

 



answered Jul 29, 2025 by avibootz
...