Fibonacci sequence

I have been trying to do this Fibonacci sequence with the default args for awhile. I keep coming up with incorrect results. The total should be 4613732. and as it goes up, the 4 should be a five, and the 7 should be an eight, etc.
1
2
3
4
5
6
7
1
2
3
4
7
11
...



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
#include <iostream>
#include <vector>
using namespace std;

vector<int> fib(int a=1, int b=2, int max=4000000){
    vector<int> v;
    long sum;
    v.push_back(a);
    v.push_back(b);
    while (a < max){
        sum = 0;
        sum = b + a;
        b = a;
        a = sum;
        v.push_back(sum);

    }
    return v;
}

int main(){
    int total = 0;
    vector<int> v;
    v = fib();
    for (int i=0; i<v.size(); i++){
        cout << v[i] << endl;
        total += v[i];
    }
    cout << "total: " << total << endl;
Let consider iterations

1) a = 1; v.push_back( a );
2) b = 2; v.push_back( b )
3) sum = 3; v.push_back( sum ); b = a ( b == 1 ); a = sum; ( a == 3 );
4). sum = 4 ( b (== 1 ) + a ( == 3 ) ); ....
Last edited on
4). sum = 4 ( b (== 1 ) + a ( == 3 ) );

i do not follow
b is equal to 1, a is equal to 3. Question: What value will have sum?
Last edited on
yeah but its not suppose to be 4.

grr, C's syntax is driving me nuts.
What you do is what you get. What is the problem?! I showed you your iterations.
Inside your while loop should be:

1
2
3
4
5

sum = a + v.back();
a = v.back();
v.push_back(sum);
Topic archived. No new replies allowed.