c++ 位集计算素数法

c++ 位集计算素数法

位集(bitset)计算是用空间换时间,这里的例子是书上的,计算1亿内的所有素数个数:

#include < iostream >
#include
< bitset >
using   namespace  std;
int  _tmain( int  argc, _TCHAR *  argv[])
{
    
/* 位集 计算1亿内的所有素数 */
    bitset
< 100000000 >* =   new  bitset < 100000000 > ;
    p
-> set ();
    
for ( int  i = 2 ;i <= 10000 ; ++ i)
        
if (p -> test(i))
            
for ( int  j = i * i;j < p -> size();j += i)
                p
-> reset(j);
    
int  num = 0 ;
    
for ( int  i = 2 ;i < 100000000 ; ++ i)
        
if (p -> test(i)){
            cout
<< i << ( num % 9 == 0   ? " \n " : "   " );
            num
++ ;
        }
    cout
<< " Prime's count: " << num << endl;
    delete[]p;
    system(
" pause " );
    
return   0 ;
}

可将
cout<<i<<(num%9==0?"\n":" ");
这一行去除,输出太耗时,呵呵。

你可能感兴趣的:(c++ 位集计算素数法)