Skip to content

Instantly share code, notes, and snippets.

@jbandela
Created December 15, 2015 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbandela/7fab41efe7cc37d7aef4 to your computer and use it in GitHub Desktop.
Save jbandela/7fab41efe7cc37d7aef4 to your computer and use it in GitHub Desktop.
Precomputed factorial
#include <numeric>
template<class T>
constexpr T cfact(unsigned f) {
return f?cfact<T>(f - 1)*f : 1;
}
template<class T>
constexpr T factorial_max_helper(T value_so_far, unsigned f) {
return std::numeric_limits<T>::max() / value_so_far < f ? f - 1 : factorial_max_helper(value_so_far*f, f + 1);
}
template<class T,size_t... Indices>
T factorial_helper(unsigned f, std::index_sequence<Indices...>) {
static constexpr T ar[] = { cfact<T>(Indices)... };
return ar[f];
}
template<class T>
T factorial(unsigned f) {
return factorial_helper<T>(f, std::make_index_sequence<factorial_max_helper<T>(1, 1) + 1>{});
}
#include <iostream>
int main() {
unsigned i = 7;
volatile auto r = factorial<int>(i);
std::cout << r << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment