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

Re: Output?

Here's an idea (if you want to try it...)

You could define an P type and a _NIL class.

class _NIL {};

[Error: Irreparable invalid markup ('<int [...] n,>') in entry. Owner must fix manually. Raw contents below.]

Here's an idea (if you want to try it...)

You could define an P type and a _NIL class.

class _NIL {};

template <int N, typename Next=NIL>
class P {};

Then try to build your prime number list as a composed type, i.e.
P<1, P<3, P<5, P<7, P<11, NIL> > > >

You could use the static assert thing to cause an error with this type in the statement, and You'll probably get a nice output of the prime numbers....

What do you think?

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