Problem in adding even-valued fibonacci numbers

Nov 2, 2014 at 6:55pm
I've written the following program..but it prints a garbage value. Why?

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
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int n=4000000;

    int fib;
    unsigned int sum=0;
    int a=0, b=1;

    for(int i=0; i<n; i++)
    {
         fib = a + b;

         if(fib%2==0)
            sum+=fib;

         a = b;
         b = fib;
    }

    cout<<sum;

    return 0;
}
Nov 2, 2014 at 7:16pm
What is the maximum value for int and unsigned int in your environment?
Nov 2, 2014 at 7:38pm
The calculated sum is out of range for int and unsigned int in just about ANY environment. The sum is HUGEEEE
Last edited on Nov 2, 2014 at 7:39pm
Topic archived. No new replies allowed.