-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfibonacci.hpp
58 lines (41 loc) · 1.05 KB
/
fibonacci.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright (c) Omar Boukli-Hacene. All rights reserved.
// Distributed under an MIT-style license that can be
// found in the LICENSE file.
// SPDX-License-Identifier: MIT
/// Problem source:
/// https://en.wikipedia.org/wiki/Fibonacci_sequence
#ifndef FORFUN_FIBONACCI_HPP_
#define FORFUN_FIBONACCI_HPP_
#include "common.hpp"
namespace forfun::fibonacci {
namespace iterative {
template <common::concepts::addition_unpromoted T>
[[nodiscard]] constexpr auto fib(T const n) noexcept -> T
{
T a{0};
for (T i{0}, b{1}; i < n; ++i)
{
T const c{a + b};
a = b;
b = c;
}
return a;
}
} // namespace iterative
namespace recursive {
template <common::concepts::addition_unpromoted T>
[[nodiscard]] constexpr auto fib(T const n) noexcept -> T
{
if (n <= T{2}) [[unlikely]]
{
if (n < T{1}) [[unlikely]]
{
return T{0};
}
return T{1};
}
return fib(n - T{2}) + fib(n - T{1});
}
} // namespace recursive
} // namespace forfun::fibonacci
#endif // FORFUN_FIBONACCI_HPP_