1 #ifndef libjmmcg_core_fibonacci_hpp
2 #define libjmmcg_core_fibonacci_hpp
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 namespace jmmcg {
25
26 namespace mpl {
27
28 template<unsigned long long N>
29 struct fibonacci {
30 typedef unsigned long long element_type;
31 static constexpr element_type n=N;
32 static constexpr element_type value=fibonacci<N-1>::value+fibonacci<N-2>::value;
33 };
34 template<>
35 struct fibonacci<1ull> {
36 typedef unsigned long long element_type;
37 static constexpr element_type n=1;
38 static constexpr element_type value=1;
39 };
40 template<>
41 struct fibonacci<0ull> {
42 typedef unsigned long long element_type;
43 static constexpr element_type n=1;
44 static constexpr element_type value=1;
45 };
46
47 template<unsigned long long N>
48 constexpr typename fibonacci<N>::element_type fibonacci<N>::n;
49 template<unsigned long long N>
50 constexpr typename fibonacci<N>::element_type fibonacci<N>::value;
51 constexpr typename fibonacci<1ull>::element_type fibonacci<1ull>::n;
52 constexpr typename fibonacci<1ull>::element_type fibonacci<1ull>::value;
53 constexpr typename fibonacci<0ull>::element_type fibonacci<0ull>::n;
54 constexpr typename fibonacci<0ull>::element_type fibonacci<0ull>::value;
55 }
56
57 namespace dyn {
58
59 struct fibonacci {
60 typedef unsigned long long element_type;
61
62
63
64
65
66
67
68 static element_type result(element_type N) noexcept(true) {
69
70
71
72
73 element_type fib_im2=0, fib_im1=1, fib_i=fib_im1+fib_im2;
74 for (element_type i=0; i<N; ++i) {
75 fib_i=fib_im1+fib_im2;
76 fib_im2=fib_im1;
77 fib_im1=fib_i;
78 }
79
80
81
82
83
84 return fib_i;
85 }
86 };
87
88 }
89
90 }
91
92 #endif