Last active
December 19, 2020 07:20
-
-
Save airglow923/70119c4afb7613ffb3a879009c7f28ec to your computer and use it in GitHub Desktop.
Factorial at compile time
This file contains 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 <concepts> | |
using ULL = unsigned long long int; | |
template <std::integral auto I> | |
struct Factorial { | |
static constexpr ULL value = I * Factorial<I - 1>::value; | |
}; | |
template <> | |
struct Factorial<0> { | |
[[maybe_unused]] | |
static constexpr ULL value = 1; | |
}; | |
template <std::integral auto I> | |
inline constexpr auto FactorialV = Factorial<I>::value; | |
// or using consteval (C++20) | |
consteval auto consteval_factorial(std::integral auto n) -> std::integral auto { | |
ULL result = 1; | |
for (; n > 1; --n) | |
result *= n; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment