到目前为止,我一直在尝试元编程:
// compiled on Ubuntu 13.04 with:
// clang++ -O3 -ftemplate-depth-8192 -fconstexpr-depth=4096 -std=c++11 -stdlib=libc++ -lcxxrt -ldl compile-time-primes.cpp -o compile-time-primes
// assembly output with:
// clang++ -S -mllvm --x86-asm-syntax=intel -O3 -ftemplate-depth-8192 -fconstexpr-depth=4096 -std=c++11 -stdlib=libc++ -lcxxrt -ldl compile-time-primes.cpp -o compile-time-primes.asm
#include <array>
#include <iostream>
template<typename T>
constexpr bool is_prime(T number, T limit, T counter)
{
return counter >= limit
? number % limit != 0
: number % counter
? is_prime(number, number / counter, counter + 2)
: false;
}
template<typename T>
constexpr bool is_prime(T n)
{
return n == 2 || n == 3 || n == 5
? true
: n <= 1 || n % 2 == 0
? false
: is_prime(n, n / 3, T{3});
}
template<size_t n>
struct print_below;
template<> struct print_below<2> { inline static void primes() { std::cout << 2; } };
template<size_t n>
struct print_below
{
inline static void primes()
{
print_below<n - 1>::primes();
constexpr bool is_n_prime = is_prime(n);
if(is_n_prime)
std::cout << ", " << n;
}
};
template <typename T, T... N>
struct primes { static const std::array<bool, sizeof...(N)> cache; };
template <typename T, typename L, T R>
struct append_param;
template <typename T, T... L, T R>
struct append_param<T, primes<T, L...>, R> { using primes = primes<T, L..., R>; };
template <size_t N>
struct indexer : append_param<size_t, typename indexer<N - 1>::primes, N - 1> {};
template <>
struct indexer<0> { using primes = primes<size_t>; };
template <typename T, T... N>
const std::array<bool, sizeof...(N)> primes<T, N...>::cache = {{ is_prime(N)... }};
int main()
{
std::cout << "Some primes: \n";
print_below<8000>::primes();
std::cout << std::endl;
const auto &primes_cache = indexer<1000>::primes::cache;
for(size_t i = 1; i < primes_cache.size(); ++i)
std::cout << i << (primes_cache[i] ? " is " : " is not ") << "prime" << std::endl;
}
现在我想知道是否有更好的尾递归算法is_prime
可以放入constexpr
函数中。
还有什么比这更好的吗?
- 要求:必须是尾递归的。
- 可取的:适合一个
constexpr
函数。