Fibonacci sequence problem

Not sure what to put in the title...

Quite recently I took to trying to solve problems on "ProjectEuler.net". It's a website with loads of maths problems to solve... I ran out of ideas for things to do a while ago and someone told me about the website. So I've been doing the problems on there.

I've written this code and it outputs the answer 627587869, which I am sure is wrong. I have no idea what is wrong with the code though (it is me, not the compiler, I am sure. I am using Dev-C++ so I know it isn't the compiler's problem).

If you're wondering why I am using long, it is because it was outputting things like -138348534578304897580346873469073086 (intense exaggeration) and I thought it might be because the number is too big for an integer, and didn't change it back.

The answer is apparantly 4613732, and I have no idea how to reach it.

Please don't write the program for me, just some tips would be good.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

long Fib() {

long fib1=0, fib2=1, fibr, n=4000000;

for (int i=n; i>0; i--) {
    fibr=fib1+fib2;
    fib1=fib2;
    fib2=fibr;
}
return fibr;
}

using namespace std;

int main() {
cout << "The sum of all even numbers in the Fibonacci sequence which are lower than four million is: " << Fib() << endl;
cin.get();
return 0;
}
Last edited on
It is because a long doesn't have enough bits to store fib(4000000). [I don't think the computer as a whole has enough bits.]

As a hint:

fib( 33 ) --> 3,524,578
fib( 34 ) --> 5,702,887


Hope this helps.
I'm not sure I understand your hint.

Thanks for helping though.
Last edited on
You want the sum of even fibonacci numbers less than 4,000,000, right?

So that's the sum of all the even numbers for n in [0,33].

Hope this helps.
Last edited on
Ohh! Thanks! Can't compile right now as I'm at school (it's 8:15AM in the UK), so I'll try that when I get home.
Topic archived. No new replies allowed.