#include //#define CONSTEXPR #ifdef CONSTEXPR #include typedef std::pair is_prime_t; constexpr is_prime_t is_prime_recursive(size_t number, size_t c, unsigned recurs) { return (c*c > number) ? is_prime_t(true,recurs) : (number % c == 0) ? is_prime_t(false,recurs) : is_prime_recursive(number, c+1, recurs+1); } constexpr is_prime_t is_prime_func(size_t number) { unsigned const recurs=1; return (number <= 1) ? is_prime_t(false,recurs) : is_prime_recursive(number, 2, recurs+1); } #else struct false_type { typedef false_type type; enum { value = 0 }; static unsigned const recurs=1; }; struct true_type { typedef true_type type; enum { value = 1 }; static unsigned const recurs=1; }; template struct if_ { typedef U type; }; template struct if_ { typedef T type; }; template struct is_prime_impl { typedef typename if_<(c*c > N), true_type, typename if_<(N % c == 0), false_type, is_prime_impl >::type >::type type; enum { value = type::value }; static unsigned const recurs=type::recurs+1; }; template struct is_prime_meta : is_prime_impl { }; template <> struct is_prime_meta<0> { enum { value = 0 }; static unsigned const recurs=1; }; template <> struct is_prime_meta<1> { enum { value = 0 }; static unsigned const recurs=1; }; #endif static bool IsPrime(size_t number) { if (number <= 1) return false; for (size_t i = 2; i*i <= number; ++i) if (number % i == 0) return false; return true; } #ifndef NUMBER #define NUMBER 104729 // #define NUMBER 7 #endif int main(void) { printf("IsPrime(%d) = %d", NUMBER, IsPrime(NUMBER)); #ifdef CONSTEXPR auto constexpr result=is_prime_func(NUMBER); printf(",\t is_prime_func(yesno,recurs)=(%d,%d)\n", result.first , result.second ); #else typedef is_prime_meta result; printf(",\t is_prime_meta(yesno,recurs)=(%d,%d)\n", result::value, result::recurs); #endif return 0; }