在错误信息里输出N以内的素数

来源:互联网 发布:linux查看iscsi盘符 编辑:程序博客网 时间:2024/05/17 22:04

以前在MCD上听说过,又见过几个讨论,忘了在哪里,也没弄清楚怎么实现的,今天中午试了一下,居然成功了,高兴ing!贴出来,与大家分享:

(VS.NET 2005)

template<long M,long N>struct CanDivid    //whether N can be divided by (2 to M)
{
    enum{Result = (N % M == 0 || CanDivid<M - 1,N>::Result)};
};
template<long N>struct CanDivid<2,N>
{
    enum{Result = (N % 2 == 0)};
};
template<long N>struct CanDivid<1,N>
{
    enum{Result = 0};
};
template<long N>struct CanDivid<0,N>
{
    enum{Result = 0};
};

template<long N>struct Prime
{    //whether N is a prime number
    enum{IsPrime = !CanDivid<N / 2,N>::Result};
    Prime();
};

template<bool R,class T1,class T2>struct Selector    //type selector
{
    typedef T1 RType;
};
template<class T1,class T2>struct Selector<false,T1,T2>
{
    typedef T2 RType;
};

template<long N>struct Generate:public Generate<N-1>
{
    typedef typename Selector<Prime<N>::IsPrime,Prime<N>,int>::RType RType;
    Generate(){
        RType();
    }
};

template<>struct Generate<2>
{
    Generate(){
        Prime<2>();
    }
};

int main(){
    Generate<100>();    //generate prime numbers from 2 to 100 in Error Message
}

作用:在错误信息里输出100以内的素数。

原创粉丝点击