Here, we will build a C Program to Find the Sum of Fibonacci numbers at even indexes up to N terms
Fibonacci Numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……
Input:
N = 5
Output:
88 // Sum of the elements at even indexes = 0 + 1 + 3 + 8 + 21 + 55 = 88
Approach:
This approach includes solving the problem directly by finding all Fibonacci numbers till 2n and adding up only the even indices numbers from the array.
Example:
C
#include <stdio.h>
int calculateEvenSum( int n)
{
if (n <= 0)
return 0;
int fibo[2 * n + 1];
fibo[0] = 0, fibo[1] = 1;
int sum = 0;
for ( int i = 2; i <= 2 * n; i++) {
fibo[i] = fibo[i - 1] + fibo[i - 2];
if (i % 2 == 0)
sum += fibo[i];
}
return sum;
}
int main()
{
int n = 5;
int sum = calculateEvenSum(n);
printf ( "Even indexed Fibonacci Sum upto %d terms = %d" ,
n, sum);
return 0;
}
|
Output
Even indexed Fibonacci Sum upto 5 terms = 88
Time Complexity: O(N)
Space Complexity: O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Oct, 2022
Like Article
Save Article