-
Notifications
You must be signed in to change notification settings - Fork 0
/
fibonacci_sequence.hpp
78 lines (58 loc) · 1.68 KB
/
fibonacci_sequence.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// 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_SEQUENCE_HPP_
#define FORFUN_FIBONACCI_SEQUENCE_HPP_
#include <concepts>
#include <utility>
namespace forfun::fibonacci::sequence {
// clang-format off
template <typename Func, typename... Args>
concept noexcept_callable
= std::invocable<Func, Args...>
and requires(Func&& func, Args&&... args) {
requires noexcept(func(std::forward<Args>(args)...));
};
// clang-format on
namespace slow {
template <std::integral T, typename State, noexcept_callable<T, State&> Func>
auto fib_seq(T const max, Func func, State& state) noexcept -> void
{
for (T i{0}, j{1}; i <= max;)
{
func(i, state);
T const aux{j + i};
i = j;
j = aux;
}
}
} // namespace slow
namespace fast {
template <std::integral T, typename State, noexcept_callable<T, State&> Func>
auto fib_seq(T const max, Func func, State& state) noexcept -> void
{
for (T i{0}, j{1}; i <= max;)
{
func(i, state);
j += i;
i = j - i;
}
}
} // namespace fast
namespace creel {
template <std::integral T, typename State, noexcept_callable<T, State&> Func>
auto fib_seq(T const max, Func func, State& state) noexcept -> void
{
// Adapted from: https://youtu.be/IZc4Odd3K2Q?t=949
for (T i{0}, j{1}; i <= max;)
{
func(i, state);
j = (i += j) - j;
}
}
} // namespace creel
} // namespace forfun::fibonacci::sequence
#endif // FORFUN_FIBONACCI_SEQUENCE_HPP_