There are two ways to implement a factorial function. The first is the conventional method using a constexpr function:
constexpr fct (unsigned n) {
return (i < 2) ? 1 : n * fct (n - 1);
}
This has the advantage in that it can be used for both compile-time and runtime computation:
constexpr unsigned x = fct (5); // compile-time computation
A good compiler will perform the complete calculation at compile-time, thus the declaration of x is equivalent to:
constexpr unsigned x = 120; // e.g. x = 5 * 4 * 3 * 2 * 1
Conversely, the declaration of y is not constexpr, thus the calculation must be performed at runtime. The same is true of any non-const variable.
However, if we only required compile-time computation, then we can use template-metaprogramming instead:
template<unsigned N>
constexpr unsigned fac (void) {
return N*fac<N-1>();
}
template<>
constexpr int fac<2> (void) {
return 2;
}
Note that we cannot use variables in a template intended for compile-time computation, hence we use a template parameter and a specialisation to enable the recursion. The specialisation for N=2 represents the end-point of recursion. We could also provide a specialisation for N=1 and N=0, however this would be superfluous given that fac<1> and fac<0> both equate to 1 and we'd never deliberately invoke these in code.
Note also that the largest integer we can represent with an unsigned integer is UINT_MAX (defined in <limits>). For a 32-bit integer this is (2^32)-1, thus fct<12> is the largest factorial we can calculate. If we use uint64 instead, then we can calculate factorials up to fct<21>. However, the larger the value of N, the less likely we can make use compile-time computation, but we can still make use of partial compile-time computation in conjunction with runtime computation if we use the constexpr version of the function.
If we wish to accommodate larger factorials, then we must either use a long double or use a user-defined type that can handle larger integers, however the latter would mean losing compile-time computation altogether.
Copyright © 2026 eLLeNow.com All Rights Reserved.