Your observation is correct, the recursive approach to calculating Fibonacci numbers in this case, if you look carefully, calculates each Fibonacci term from the very beginning, i.e.
To calculate F [n] + F [n-1], for example, the function calculates both terms separately and performs the same task several times.
: F [5] = F [4] + F [3]
F [3]: : F [2], F [1], F [1], F [0]
F [4]: : F [2], F [2], F [1], F [1], F [0], F [0] F [3]/p >
:

, , , : O (2 n).
- memoization:
#include <map>
int mem_fact (int i, std::map<int, int>& m)
{
if (m.find(i) == m.end())
{
m[i] = mem_fact (i - 1, m) + mem_fact (i - 2, m);
}
return m[i];
}
int fast_factorial (int i)
{
std::map<int, int> memo;
memo.insert(std::pair<int,int>(0, 0));
memo.insert(std::pair<int,int>(1, 1));
return mem_fact(i, memo);
}
: main() fast_factorial(num_of_fib);