Calculate the Fibonacci number (recursive approach) in compile time (constexpr) in C++11

前端 未结 4 895
耶瑟儿~
耶瑟儿~ 2020-12-09 06:33

I wrote the program Fibonacci number calculation in compile time (constexpr) problem using the template metaprogramming techniques supported in C++11. The purpose of this i

4条回答
  •  庸人自扰
    2020-12-09 07:03

    The reason is that your runtime solution is not optimal. For every fib number, functions are called several times. The fibonacci sequence, has overlapping subproblems, so for example fib(6) calls fib(4), and fib(5) also calls fib(4).

    The template based approach, uses (inadvertently) a Dynamic Programming approach, meaning that it stores values for previously calculated numbers, avoiding repetition. So, when fib(5) calls fib(4), the number was already calculated when fib(6) did.

    I recommend looking up "dynamic programming fibonacci" and trying that, it should speed things up dramatically.

提交回复
热议问题