Skip to content

Instantly share code, notes, and snippets.

@airglow923
Last active December 19, 2020 07:20
Show Gist options
  • Save airglow923/70119c4afb7613ffb3a879009c7f28ec to your computer and use it in GitHub Desktop.
Save airglow923/70119c4afb7613ffb3a879009c7f28ec to your computer and use it in GitHub Desktop.
Factorial at compile time
#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