Skip to content

Instantly share code, notes, and snippets.

@lambday
Last active December 22, 2016 12:28
Show Gist options
  • Select an option

  • Save lambday/de52cc3f0671f6f959eceba3578935f2 to your computer and use it in GitHub Desktop.

Select an option

Save lambday/de52cc3f0671f6f959eceba3578935f2 to your computer and use it in GitHub Desktop.
#include <array>
#include <algorithm>
#include <numeric>
#include <vector>
namespace tmp
{
template <unsigned int N>
struct factorial
{
static constexpr unsigned int value = N * factorial<N - 1>::value;
};
template <>
struct factorial<0>
{
static constexpr unsigned int value = 1;
};
template <std::size_t N, typename T>
struct factorials_in_range_impl;
template <std::size_t N, std::size_t... Is>
struct factorials_in_range_impl<N, std::index_sequence<Is...>>
{
auto operator()() const
{
return std::array<unsigned int, N>{{factorial<static_cast<unsigned int>(Is)>::value...}};
}
};
template <std::size_t N, typename Indices = std::make_index_sequence<N>>
auto factorials_in_range()
{
factorials_in_range_impl<N, Indices> functor;
return functor();
}
}
// namespace normal
// {
// int factorial(unsigned int N)
// {
// if (N == 0)
// {
// return 1;
// }
// return N * factorial(N - 1);
// }
// auto factorials_in_range(const std::size_t N)
// {
// std::vector<unsigned int> a(N);
// std::iota(a.begin(), a.end(), 0);
// std::vector<unsigned int> factorials(N);
// std::transform(a.begin(), a.end(), factorials.begin(), [](auto& value) { return factorial(value); });
// return factorials;
// }
// }
int main()
{
auto factorials = tmp::factorials_in_range<10>();
// auto factorials = normal::factorials_in_range(10);
return std::accumulate(factorials.begin(), factorials.end(), 0);
}
main:
mov eax, 409114
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment