| 16 | } |
| 17 | |
| 18 | unsigned long long fib(size_t n) |
| 19 | { |
| 20 | // Initialise fib(i) and fib(i+1) for the first iteration of the loop where i == 0 |
| 21 | unsigned long long fib_i{0}; // fib(i) = fib(0) = 0 |
| 22 | unsigned long long fib_i_1{1}; // fib(i+1) = fib(1) = 1 |
| 23 | |
| 24 | for (size_t i{}; i < n; ++i) |
| 25 | { |
| 26 | auto fib_i_2{ fib_i + fib_i_1 }; // fib(i+2) = fib(i) + fib(i+1) |
| 27 | |
| 28 | // Get ready for the next iteration (mind the order!): |
| 29 | fib_i = fib_i_1; |
| 30 | fib_i_1 = fib_i_2; |
| 31 | } |
| 32 | |
| 33 | // At the end of the loop, i was equal to n, so fib(i) == fib(n), which is what we needed |
| 34 | return fib_i; |
| 35 | } |