JavaScript Program to Sum of Fibonacci Numbers at Even Indexes up to N Terms
Last Updated :
19 Feb, 2024
Improve
Fibonacci numbers are a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. In this article, we will explore how to calculate the sum of Fibonacci numbers at even indexes up to N terms using JavaScript.
Sum of Fibonacci Numbers at Even Indexes up to N Terms using Iteration
The basic method is to use a loop to generate Fibonacci numbers up to N terms and sum the numbers at even indexes.
function sumEvenFibonacci(n) {
if (n <= 0) return 0;
let sum = 0;
let a = 0, b = 1;
for (let i = 1; i <= n; i++) {
if (i % 2 === 0) {
sum += b;
}
[a, b] = [b, a + b];
}
return sum;
}
// Driver code
const n = 10;
console.log(`Sum of Fibonacci Numbers: ${sumEvenFibonacci(n)}`);
Output
Sum of Fibonacci Numbers: 88
Sum of Fibonacci Numbers at Even Indexes up to N Terms using Recursion
We can also use recursion to calculate Fibonacci numbers and sum the even-indexed terms. However, this approach might be less efficient for larger values of N due to the overhead of recursive calls.
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
function sumEvenFibonacci(n) {
let sum = 0;
for (let i = 2; i <= n; i += 2) {
sum += fibonacci(i);
}
return sum;
}
// Driver code
const n = 10;
console.log(`Sum of Fibonacci Numbers: ${sumEvenFibonacci(n)}`);
Output
Sum of Fibonacci Numbers: 88
Sum of Fibonacci Numbers at Even Indexes up to N Terms using Dynamic Programming
To optimize the recursive approach, we can use dynamic programming to store the Fibonacci numbers as we calculate them, reducing the number of calculations needed.
function sumEvenFibonacci(n) {
if (n <= 0) return 0;
let fib = [0, 1];
let sum = 0;
for (let i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
if (i % 2 === 0) {
sum += fib[i];
}
}
return sum;
}
// Driver code
const n = 10;
console.log(`Sum of Fibonacci Numbers: ${sumEvenFibonacci(n)}`);
Output
Sum of Fibonacci Numbers: 88