Skip to content

Instantly share code, notes, and snippets.

@johnmcfarlane
Created January 4, 2025 13:00
Show Gist options
  • Save johnmcfarlane/2eaf9d426b08281e31bebfb54c229c3a to your computer and use it in GitHub Desktop.
Save johnmcfarlane/2eaf9d426b08281e31bebfb54c229c3a to your computer and use it in GitHub Desktop.
C++20 factorial function
#include <algorithm>
#include <cassert>
#include <concepts>
#include <ranges>
[[nodiscard]] constexpr auto factorial(std::integral auto n) {
assert(n >= 0);
if (n == 0) {
return 1;
}
return std::ranges::fold_left(std::ranges::iota_view(1, n), n,
std::multiplies{});
}
static_assert(factorial(0) == 1);
static_assert(factorial(1) == 1);
static_assert(factorial(2) == 2);
static_assert(factorial(3) == 6);
static_assert(factorial(4) == 24);
static_assert(factorial(5) == 120);
static_assert(factorial(6) == 720);
static_assert(factorial(7) == 5'040);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment