素数を求める世界最速プログラム for C++
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
template <unsigned int Val> struct UintType {
enum { value = Val };
};
template <bool Val> struct BoolType {
enum { value = Val };
};
template <unsigned int PrimeNum> struct GetPrime;
template <unsigned int PrimeCount> struct NextPrimeSub1;
template <unsigned int Rest> struct NextPrimeSub3 {
template <unsigned int PrimeCount, unsigned int Cand,
unsigned int PrimeNum> struct set_state
: NextPrimeSub1<PrimeCount - 1>
::template set_state<Cand, PrimeNum + 1> {};
};
template <> struct NextPrimeSub3<0> {
template <unsigned int PrimeCount, unsigned int Cand,
unsigned int PrimeNum> struct set_state
: NextPrimeSub1<PrimeNum + PrimeCount>
::template set_state<Cand + 2, 0> {};
};
template <bool Over> struct NextPrimeSub2 {};
template <> struct NextPrimeSub2<true> {
template <unsigned int PrimeCount, unsigned int Cand,
unsigned int PrimeNum> struct set_state
: UintType<Cand> {};
};
template <> struct NextPrimeSub2<false> {
template <unsigned int PrimeCount, unsigned int Cand,
unsigned int PrimeNum> struct set_state
: NextPrimeSub3<(Cand % GetPrime<PrimeNum>::value)>
::template set_state<PrimeCount, Cand, PrimeNum> {};
};
素数を求める世界最速プログラム for C++ (続き)
template <unsigned int PrimeCount> struct NextPrimeSub1 {
template <unsigned int Cand, unsigned int PrimeNum> struct set_state
: NextPrimeSub2<(GetPrime<PrimeNum>::value * 3 > Cand)>
::template set_state<PrimeCount, Cand, PrimeNum> {};
};
template <> struct NextPrimeSub1<0> {
template <unsigned int Cand, unsigned int PrimeNum> struct set_state
: UintType<Cand> {};
};
template <unsigned int PrimeNum> struct GetPrime
: NextPrimeSub1<PrimeNum - 1>
::template set_state<GetPrime<PrimeNum - 1>::value + 2, 0> {};
template <> struct GetPrime<0> : UintType<2> {};
template <> struct GetPrime<1> : UintType<3> {};
#define PRIME(n) (GetPrime<n>::value)
static unsigned int prime_array[] = {
PRIME(0), PRIME(1), PRIME(2), PRIME(3), PRIME(4),
PRIME(5), PRIME(6), PRIME(7), PRIME(8), PRIME(9),
PRIME(10), PRIME(11), PRIME(12), PRIME(13), PRIME(14),
PRIME(15), PRIME(16), PRIME(17), PRIME(18), PRIME(19),
PRIME(20), PRIME(21), PRIME(22), PRIME(23), PRIME(24),
PRIME(25), PRIME(26), PRIME(27), PRIME(28), PRIME(29),
PRIME(30), PRIME(31), PRIME(32), PRIME(33), PRIME(34),
PRIME(35), PRIME(36), PRIME(37), PRIME(38), PRIME(39),
PRIME(40), PRIME(41), PRIME(42), PRIME(43), PRIME(44),
PRIME(45), PRIME(46), PRIME(47), PRIME(48), PRIME(49),
};
enum { n_prime_array = sizeof prime_array / sizeof *prime_array };
struct PutUint : unary_function<unsigned int, void> {
void operator()(unsigned int val) {
cout << val << endl;
}
};
int main() {
for_each(prime_array, prime_array + n_prime_array, PutUint());
return 0;
}
マクロアセンブラでこーゆーネタがあったらしいけど・・・。