Project Euler #2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

I'm a pretty bad programmer so I'm trying to get better by doing these problems. At first I got an answer of around 2 million but I think that is the wrong answer (i took a peek somewhere online and the answer is around 4.1 million). I edited my code and now I keep on getting 0. I DONT KNOW WHATS WRONG and it's bothering me a lot......... please help!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using namespace std;
int initialfib1;
int initialfib2;
int nextfib = 0;

int fibfunc(int initialfib1,int initialfib2)
{
    int n;
    //define a function that defines the fibonacci sequence
    while(nextfib<4000000)
        {
                if(nextfib%2 == 0)
                    {
                        n = nextfib;
                        n += n;
                    }
            nextfib = initialfib1 + initialfib2;
            initialfib1 = initialfib2;
            initialfib2 = nextfib;
            fibfunc(initialfib1, initialfib2);
        }
    return n;
}

int main()

{
    int x;
    x = fibfunc(0,1);
    cout << x;
}
Well, ints can only store values up to positive 2 million ish, so if there are Fibonacci numbers that are above that but below 4 million you'll get an incorrect answer.
@firedraco: int can store up to 2^31 about 2 billions.

@liondancer: you return twice of the largest even Fibonacci number. You should replace
1
2
3
4
5
                if(nextfib%2 == 0)
                    {
                        n = nextfib;
                        n += n;
                    }
with something similar to
if(nextfib%2 == 0) n += nextfib;

Also, I think that the call fibfunc(initialfib1, initialfib2); is extra.
And don't forget to initialize n.
Topic archived. No new replies allowed.