1 // Copyright 2020, Madhur Chauhan
3 // Use, modification and distribution are subject to the
4 // Boost Software License, Version 1.0.
5 // (See accompanying file LICENSE_1_0.txt
6 // or copy at http://www.boost.org/LICENSE_1_0.txt)
8 #ifndef BOOST_MATH_SPECIAL_FIBO_HPP
9 #define BOOST_MATH_SPECIAL_FIBO_HPP
11 #include <boost/math/constants/constants.hpp>
12 #include <boost/math/policies/error_handling.hpp>
24 constexpr double fib_bits_phi = 0.69424191363061730173879026;
25 constexpr double fib_bits_deno = 1.1609640474436811739351597;
29 inline BOOST_CXX14_CONSTEXPR T unchecked_fibonacci(unsigned long long n) noexcept(std::is_fundamental<T>::value) {
30 // This function is called by the rest and computes the actual nth fibonacci number
31 // First few fibonacci numbers: 0 (0th), 1 (1st), 1 (2nd), 2 (3rd), ...
32 if (n <= 2) return n == 0 ? 0 : 1;
34 * This is based on the following identities by Dijkstra:
35 * F(2*n) = F(n)^2 + F(n+1)^2
36 * F(2*n+1) = (2 * F(n) + F(n+1)) * F(n+1)
37 * The implementation is iterative and is unrolled version of trivial recursive implementation.
39 unsigned long long mask = 1;
40 for (int ct = 1; ct != std::numeric_limits<unsigned long long>::digits && (mask << 1) <= n; ++ct, mask <<= 1)
43 for (mask >>= 1; mask; mask >>= 1) {
45 a = 2 * a * b - t1, b = b * b + t1;
47 t1 = b, b = b + a, a = t1; // equivalent to: swap(a,b), b += a;
52 template <typename T, class Policy>
53 T inline BOOST_CXX14_CONSTEXPR fibonacci(unsigned long long n, const Policy &pol) {
54 // check for overflow using approximation to binet's formula: F_n ~ phi^n / sqrt(5)
55 if (n > 20 && n * detail::fib_bits_phi - detail::fib_bits_deno > std::numeric_limits<T>::digits)
56 return policies::raise_overflow_error<T>("boost::math::fibonacci<%1%>(unsigned long long)", "Possible overflow detected.", pol);
57 return unchecked_fibonacci<T>(n);
61 T inline BOOST_CXX14_CONSTEXPR fibonacci(unsigned long long n) {
62 return fibonacci<T>(n, policies::policy<>());
65 // generator for next fibonacci number (see examples/reciprocal_fibonacci_constant.hpp)
67 class fibonacci_generator {
69 // return next fibonacci number
70 T operator()() noexcept(std::is_fundamental<T>::value) {
72 a = b, b = b + ret; // could've simply: swap(a, b), b += a;
76 // after set(nth), subsequent calls to the generator returns consecutive
77 // fibonacci numbers starting with the nth fibonacci number
78 void set(unsigned long long nth) noexcept(std::is_fundamental<T>::value) {
80 a = unchecked_fibonacci<T>(n);
81 b = unchecked_fibonacci<T>(n + 1);
85 unsigned long long n = 0;