Skip to content

Instantly share code, notes, and snippets.

@odanado
Last active August 29, 2015 14:03
Show Gist options
  • Save odanado/33887b3e69c4a28e6652 to your computer and use it in GitHub Desktop.
Save odanado/33887b3e69c4a28e6652 to your computer and use it in GitHub Desktop.
O(sqrt(n))
#include <iostream>
template<bool Cond>
struct bool_;
template<>
struct bool_<true> {
static const bool value = true;
};
template<>
struct bool_<false> {
static const bool value = false;
};
template<bool Cond, class Then, class Else>
struct if_;
template<class Then, class Else>
struct if_<true, Then, Else> {
typedef Then type;
};
template<class Then, class Else>
struct if_<false, Then, Else> {
typedef Else type;
};
template<class T, T arg0, T arg1>
struct lt {
static const bool value = arg0 < arg1;
};
template<int N, int M>
struct is_prime {
static const bool value =
if_< lt<int,N,M*M>::value, bool_<true>,
typename if_< (N%M==0) ,bool_<false>, is_prime<N,M+1> >::type >::type::value;
};
int main() {
if(is_prime<1009,2>::value) {
std::cout<<"prime"<<std::endl;
}
else {
std::cout<<"not prime"<<std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment