Skip to content

Instantly share code, notes, and snippets.

@tahsinkose
Created August 10, 2018 17:06
Show Gist options
  • Save tahsinkose/be1be0cf29a982b562e2f59403c52ed6 to your computer and use it in GitHub Desktop.
Save tahsinkose/be1be0cf29a982b562e2f59403c52ed6 to your computer and use it in GitHub Desktop.
#include <iostream>
#define N 1000
/*
This is quite a good example of Template Meta Programming. Especially, in hackathons that accept executables or does not have
time limit in compilation, computation-heavy tasks as prime num discovery in a range can be hacked in compile time. And the result
can be expressed in O(1) or O(n) with some reasonable constant factor.
Reference: https://en.wikibooks.org/wiki/C%2B%2B_Programming/Templates/Template_Meta-Programming
*/
template <int p,int i>
class is_prime {
public:
enum {prim = ((p%i) && is_prime<p,i-1>::prim)};
};
template<int p>
class is_prime<p,1>{
public:
enum {prim = 1};
};
template <int i>
class Prime_print {
public:
Prime_print<i-1> a;
enum { prim = is_prime<i,i-1>::prim};
void f(){
a.f();
if(prim)
std::cout<<"prime number: "<<i<<std::endl;
}
};
template<>
class Prime_print<1> {
public:
enum {prim = 0};
void f(){}
};
int main(){
Prime_print<N> a;
a.f();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment