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

前端 未结 4 910
耶瑟儿~
耶瑟儿~ 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 06:52

    Maybe just use a more efficient algorithm?

    constexpr pair helper(size_t n, const pair& g)
    {
        return n % 2
            ? make_pair(g.second * g.second + g.first * g.first, g.second * g.second + 2 * g.first * g.second)
            : make_pair(2 * g.first * g.second - g.first * g.first, g.second * g.second + g.first * g.first);
    }
    
    constexpr pair fibonacciRecursive(size_t n)
    {
        return n < 2
            ? make_pair(n, 1)
            : helper(n, fibonacciRecursive(n / 2));
    }
    
    constexpr double fibonacci(size_t n)
    {
        return fibonacciRecursive(n).first;
    }
    

    My code is based on an idea described by D. Knuth in the first part of his "The Art of Computer Programming". I can't remember the exact place in this book, but I'm sure that the algorithm was described there.

提交回复
热议问题