Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compute prime number by C++ compiler.
#include <iostream>
struct true_type {static const bool value = true;};
struct false_type {static const bool value = false;};
template<bool, bool ...Args>
struct and_ : false_type {};
template<bool ...Args>
struct and_<true,Args...> {static const bool value = and_<Args...>::value; };
template<>
struct and_<true> : true_type {};
template<>
struct and_<false> : false_type {};
template<unsigned int L, unsigned int R>
struct modulo {static const bool value = L % R == 0; };
template<unsigned int TEST, unsigned int DIVIDEND>
struct __is_prime : and_<!modulo<TEST, DIVIDEND>::value, __is_prime<TEST, DIVIDEND-1>::value> {};
template<unsigned int TEST>
struct __is_prime<TEST, 1> : true_type {};
template<unsigned int T>
struct is_prime : __is_prime<T, T-1> {};
template<>
struct is_prime<2> : true_type {};
int main()
{
std::cout << std::boolalpha << is_prime<2>::value << std::endl;
std::cout << std::boolalpha << is_prime<3>::value << std::endl;
std::cout << std::boolalpha << is_prime<4>::value << std::endl;
std::cout << std::boolalpha << is_prime<5>::value << std::endl;
std::cout << std::boolalpha << is_prime<10>::value << std::endl;
std::cout << std::boolalpha << is_prime<11>::value << std::endl;
std::cout << std::boolalpha << is_prime<12>::value << std::endl;
std::cout << std::boolalpha << is_prime<13>::value << std::endl;
std::cout << std::boolalpha << is_prime<49>::value << std::endl;
std::cout << std::boolalpha << is_prime<197>::value << std::endl;
std::cout << std::boolalpha << is_prime<203>::value << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.