Maxim Dementiev's Blog

All posts are open. You are welcome to comment. Come on! :-)

Previous Entry Share Next Entry
Computing prime numbers during compilation, from-other-end version

Русская версия

The canonical variant checks by the division, but I decided to create all multiplication variants and then to enumerate numbers for which there is no such variant.
As usual, I've learned a lot...
template<int N, int J=N, int I=N> struct K;

template<int N, int I> struct K<N, 1, I>
    void not_prim();

template<int N, int J> struct K<N, J, 1> : public K<N, J-1, N/(J-1) + 1>
    using K<N, J-1, N/(J-1) + 1>::not_prim;
    K() { char a[J] = {0}; not_prim(a); }

template<int N, int J, int I> struct K : public K<N, J, I-1>
    using K<N, J, I-1>::not_prim;
    typedef const char A[J*I];
    virtual void not_prim(const A &) const;

int main()
    K<55> k;

Generated by GNU Source-highlight 2.9

In fact, this is an implementation of the Sieve of Eratosthenes.

  • 1
First, I would like to thank every one who sent me the feed-back! :-)
And I hope it's interesting.

No doubt, this sample could be improved.
There is always something to improve.

But I don't think it really needs modifications: being simple and compiler/environment/platform-independent, it just works!

  • 1

Log in

No account? Create an account