Created
January 4, 2025 13:00
-
-
Save johnmcfarlane/2eaf9d426b08281e31bebfb54c229c3a to your computer and use it in GitHub Desktop.
C++20 factorial function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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