The Fibonacci sequence starts with 0, 1, and each subsequent number is the sum of the previous two numbers. The task is to find the sum of Fibonacci numbers present at even indexes from 0 to 2N.
Fibonacci Sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Example:
For N = 5, the even indexes are 0, 2, 4, 6, 8, 10.
Therefore:
F(0) + F(2) + F(4) + F(6) + F(8) + F(10)
= 0 + 1 + 3 + 8 + 21 + 55
= 88
Approach
Generate the Fibonacci sequence up to index 2N and add the numbers whose indexes are even.
- Initialize the first two Fibonacci numbers as 0 and 1.
- Generate Fibonacci numbers up to index 2N.
- Add the Fibonacci number whenever its index is even.
- Return the calculated sum.
#include <stdio.h>
// Calculates the sum of Fibonacci numbers at even indexes
int calculateEvenSum(int n)
{
if (n < 0)
return 0;
int fibo[2 * n + 1];
// Initialize the first two Fibonacci numbers
fibo[0] = 0;
fibo[1] = 1;
int sum = fibo[0];
// Generate Fibonacci numbers up to index 2n
for (int i = 2; i <= 2 * n; i++) {
fibo[i] = fibo[i - 1] + fibo[i - 2];
// Add Fibonacci numbers at even indexes
if (i % 2 == 0)
sum += fibo[i];
}
return sum;
}
int main()
{
int n = 5;
// Calculate the sum of even-indexed Fibonacci numbers
int sum = calculateEvenSum(n);
printf("Sum of Fibonacci numbers at even indexes = %d", sum);
return 0;
}
Output
Sum of Fibonacci numbers at even indexes = 88
Explanation
- The array stores Fibonacci numbers from index 0 to 2n.
- The loop generates each Fibonacci number using the previous two values.
- Fibonacci numbers at even indexes are added to sum.