Member Avatar for Member #866461

trying to do a program that sums all the even numbers in the sequence but i think im doing it wrong

heres my code

#include <stdio.h>
int fib ( int n );
int main ( int argc, char *argv[ ] ) {


int i , sum = 0 ;

for(i = 1; i <= 6 ;++i) {

int v = fib(i) ;

if( (v % 2) == 0 ) {

sum = sum + i ;

}

}

printf("the sum is %d",sum) ;

return 0 ;

}

int fib(int n) {

if ( n == 1 || n == 2) return 1 ;

else

return fib(n - 1) + fib( n - 2 ) ;

}

Dani AI

Generated

Building on 's pointer to the immediate fix, here are practical improvements and things to watch when summing even Fibonacci numbers (and quick, ready-to-run examples).

Every third Fibonacci number is even. Let E1=2, E2=8, then the even subsequence satisfies the linear recurrence
Ek = 4*E{k-1} + E_{k-2}.
That lets code jump three indices at a time and avoid computing every Fibonacci term. This is both faster and simpler than naive recursive Fibonacci.

A compact C example that sums even Fibonacci values up to a given limit (uses 64-bit integers):

#include <stdio.h>
#include <stdint.h>

int main(void) {
    int64_t limit = 4000000;
    int64_t a = 2, b = 8;     /* E1, E2 */
    int64_t sum = 0;

    while (a <= limit) {
        sum += a;
        int64_t c = 4*b + a;  /* next even fib */
        a = b;
        b = c;
    }

    printf("%lld\n", (long long)sum);
    return 0;
}

Python version using the same recurrence:

def sum_even_fib(limit):
    a, b = 2, 8
    total = 0
    while a <= limit:
        total += a
        a, b = b, 4*b + a
    return total

print(sum_even_fib(4000000))  # 4613732

Notes: avoid naive recursion (very slow for larger indices); use this recurrence or an iterative loop for O(n) / O(k) performance. Watch integer overflow in C — signed 64-bit covers up to about F92; use a bigger integer type or a bignum library for larger limits. For background on the sequence see Fibonacci number - Wikipedia and the classic sum-under-a-limit example at Project Euler Problem 2.

Recommended Answers

All 2 Replies

Are you summing the actual values in the sequence or the index within the sequence? Because your code presently does the latter by adding i to the sum instead of v .

Member Avatar for Member #866461

yea just noticed that lol thanks it works now

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.