Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
C++ program that calculates prime numbers during compile time
#1
    C++-Code:
#include <utility>
#include <iostream>
#include <type_traits>
 
template <typename T>
struct type_is { using type = T; };
 
namespace detail {
 
template <size_t N,typename>
struct SIsPrime;
 
template <size_t N>
struct SIsPrime<N,std::index_sequence<>>:std::true_type {};
 
template <size_t N,size_t M,size_t... Ms>
struct SIsPrime<N,std::index_sequence<M,Ms...>>
    :std::conditional<N%(M+2) == 0,std::false_type,SIsPrime<N,std::index_sequence<Ms...>>>::type {};
 
}
 
template <size_t N>
struct is_prime;
 
template <>
struct is_prime<0>:std::false_type {};
 
template <>
struct is_prime<1>:std::false_type {};
 
template <size_t N>
struct is_prime:detail::SIsPrime<N,std::make_index_sequence<N/2-1>> {};
 
template <typename NumberTs,typename PrimeTs = std::index_sequence<>>
struct filter_primes;
 
template <size_t... Primes>
struct filter_primes<std::index_sequence<>,
                     std::index_sequence<Primes...>>:type_is<std::index_sequence<Primes...>> {};
 
template <size_t N,size_t... Numbers,size_t... Primes>
struct filter_primes<std::index_sequence<N,Numbers...>,std::index_sequence<Primes...>>
    :std::conditional<is_prime<N>::value,
                          filter_primes<std::index_sequence<Numbers...>,std::index_sequence<Primes...,N>>,
                          filter_primes<std::index_sequence<Numbers...>,std::index_sequence<Primes...>>>::type {};
 
template <typename>
struct print_index_sequence;
 
template <size_t N>
struct print_index_sequence<std::index_sequence<N>> {
    static inline void call(){
        std::cout << N;
    };
};
 
template <size_t N,size_t... Ns>
struct print_index_sequence<std::index_sequence<N,Ns...>> {
    static inline void call(){
        std::cout << N << ", ";
        print_index_sequence<std::index_sequence<Ns...>>::call();
    };
};
 
template<>
struct print_index_sequence<std::index_sequence<>> {
    static inline void call(){};
};
 
int main(){
    using Numbers = std::make_index_sequence<600>;
    using Primes = filter_primes<Numbers>::type;
 
    print_index_sequence<Primes>::call();
 
    return 0;
}


Requires a C++14 compiler and library. If it takes too long time to compile you can change the maximal number from 600 to something smaller.
Age ratings for movies and games (and similar) have never been a good idea.
One can learn a lot from reinventing wheels.
An unsound argument is not the same as an invalid one.
volatile in C++ does not mean thread-safe.
Do not make APIs unnecessarily asynchronous.
Make C++ operator > again
Trump is an idiot.
Reply
Thanks given by: A-Man , MangaD




Users browsing this thread: 1 Guest(s)