C ++ 11 constexpr version, which should be able to check numbers up to about 1500 on any compiler that implements the proposed recursion depth limit:
constexpr bool is_prime_helper( std::size_t target, std::size_t check ) { return (check*check > target) || ( (target%(check+1) != 0) && (target%(check+5) != 0) && is_prime_helper( target, check+6 ) ); } constexpr bool is_prime( std::size_t target ) { return (target != 0) && (target !=1) && ( ( target == 2 || target == 3 || target == 5 ) || ((target%2 != 0) && (target%3 != 0) && (target%5)!=0 && is_prime_helper( target, 6 ))); }
to improve this, we had some fun in the binary search tree:
#include <cstddef> constexpr bool any_factors( std::size_t target, std::size_t start, std::size_t step) { return !(start*start*36 > target) && ( ( (step==1) && ( (target%(start*6+1) == 0) || (target%(start*6+5) == 0) ) ) || ( (step > 1) && ( any_factors( target, start, step/2 ) || any_factors( target, start+step/2, step/2 ) ) ) ); }
which we then use as follows:
constexpr bool is_prime( std::size_t target ) {
which will be recursive ~ log_2(target/6) times, which means that the recursion limit in constexpr expressions 512, which are standard C ++ 11 queries that compilers execute at least, is no longer a problem.
Live example , with debugging built-in.
This will work mainly with std::size_t restrictions on your system. I tested it with 111111113 .
Yakk source share