Skip to content

Commit

Permalink
Add iterative nth Fibonacci finder
Browse files Browse the repository at this point in the history
  • Loading branch information
oboukli committed Mar 7, 2024
1 parent 6d07986 commit e04ba81
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 13 deletions.
11 changes: 10 additions & 1 deletion benchmark/fibonacci_benchmark.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,19 @@ TEST_CASE("fibonacci benchmarking", "[benchmark][fibonacci]")
.title("Fibonacci number")
.relative(true)

.run(
NAMEOF_RAW(iterative::fib<std::uint_fast32_t>).c_str(),
[]() {
auto const r{iterative::fib(n)};

ankerl::nanobench::doNotOptimizeAway(r);
})

.run(
NAMEOF_RAW(recursive::fib<std::uint_fast32_t>).c_str(),
[]() {
auto r{recursive::fib(n)};
auto const r{recursive::fib(n)};

ankerl::nanobench::doNotOptimizeAway(r);
})

Expand Down
21 changes: 21 additions & 0 deletions include/forfun/fibonacci.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,27 @@

namespace forfun::fibonacci {

namespace iterative {

template <typename T>
requires std::integral<T>
and std::is_same_v<T, decltype(std::declval<T>() + std::declval<T>())>
[[nodiscard]] constexpr inline T fib(T const n) noexcept
{
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 <typename T>
Expand Down
22 changes: 10 additions & 12 deletions test/fibonacci_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,35 @@

// SPDX-License-Identifier: MIT

#include <catch2/catch_template_test_macros.hpp>
#include <catch2/catch_test_macros.hpp>

#include "forfun/fibonacci.hpp"

TEST_CASE("Find Fibonacci number", "[fibonacci]")
TEMPLATE_TEST_CASE_SIG(
"Find Fibonacci number",
"[fibonacci]",
((auto fib), fib),
(forfun::fibonacci::iterative::fib<int>),
(forfun::fibonacci::recursive::fib<int>))
{
using forfun::fibonacci::recursive::fib;

SECTION("Negative value case (n = -1)")
{
constexpr auto const n{-1};

CAPTURE(n);
static constexpr int const n{-1};

STATIC_REQUIRE(fib(n) == 0);
}

SECTION("First (zeroth) Fibonacci number (n = 0) is zero")
{
constexpr auto const n{0};

CAPTURE(n);
static constexpr int const n{0};

STATIC_REQUIRE(fib(n) == 0);
}

SECTION("Second Fibonacci number (n = 1) is one")
{
constexpr auto const n{1};

CAPTURE(n);
static constexpr int const n{1};

STATIC_REQUIRE(fib(n) == 1);
}
Expand Down

0 comments on commit e04ba81

Please sign in to comment.