MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / fib

Function fib

Exercises/Modules/Chapter 08/Soln8_07A.cpp:18–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

16}
17
18unsigned 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}

Callers 1

mainFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected