0

I got the following piece code to generate Fibonacci series but I cannot make sense of it, what is the math methodology behind it?

Here is the code: comes from 5.3 of Quant Job Interview Questions and Answers by Mark Joshi

int Fib2(int N):
{
    std::vector<int> v(3);
    v[0] = 1;
    v[1] = 1;
    for (int j = 0; j<=N-2; ++j)
      v[(j+2)%3] = v[(j+1)%3] + v[(j)%3];
    return v[N%3];
}

Also, what is the meaning of std::vector in the above code?

genpfault
  • 51,148
  • 11
  • 85
  • 139
M00000001
  • 309
  • 2
  • 10
  • Well, `std::vector` is refferring to [this](https://en.cppreference.com/w/cpp/container/vector). –  Nov 15 '19 at 19:38
  • 3-5 months should be sufficient for this. The application of the modulo operator effectively gives you a three slot [circular buffer](https://en.wikipedia.org/wiki/Circular_buffer). – user4581301 Nov 15 '19 at 19:43

1 Answers1

3

An std::vector is a container (similar to an array). In this case, it's storing 3 integers. Essentially, they're trying to be fancy and not use 3 int variables that they constantly reassign every loop (which would be simpler/more readable code).

To calculate a Fib number, you need to sum the last two Fib numbers. So we really only need 3 integers at a time: the last two Fib numbers, and then another integer to store our new Fib number.

We're using modulo here to tell us which index is which. So the vector will look like this through the loops: (the star denotes the index we just calculated and assigned)

+--------------------------+
| Fib(0) | Fib(1) | *Fib(2)|
+--------------------------+
|   1    |   1    |    2   |
+--------------------------+

+--------------------------+
|*Fib(3) | Fib(1) | Fib(2) |
+--------------------------+
|   3    |   1    |    2   |
+--------------------------+

+--------------------------+
| Fib(3) | *Fib(4) | Fib(2)|
+--------------------------+
|   3    |   5     |   2   |
+--------------------------+

etc...

A simpler implementation with 3 integers (that's functionally the same as this) would look like:

int Fib2(int N) {
    int last, curr;
    last = curr = 1;

    for (int j = 0; j<=N-2; ++j) {
      int newest = last + curr;
      last = curr, curr = newest;
    }
    return curr;
}
scohe001
  • 15,110
  • 2
  • 31
  • 51
  • Good answer, except the OP expressed not knowing what a `std::vector` is. Thus, a [link to its documentation](https://en.cppreference.com/w/cpp/container/vector) might be helpful and would make your answer that much better. –  Nov 15 '19 at 19:49
  • Ahh I interpreted that to be confusion around what the vector was being used for. I can throw that in though, @Chip. Thanks! – scohe001 Nov 15 '19 at 19:50