zoukankan      html  css  js  c++  java
  • 位处理的低级筛法

    不得不说位操作是件很神奇的东西

    //低级筛法
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<ctime>
    using namespace std;
    int _count(unsigned int a){
        int sum=0;
        for(unsigned int x=a;x;x>>=1)
            if(x&1) sum++;
        return sum;
    }
    void sieve(unsigned int* p){
        for(int i=2;i<=10000;++i)
            if(p[i/32]&(1<<i%32))//i/32位第i/32个整数;i%32为第i/32个整数的第i%32位
                for(int j=i*i;j<100000000;j+=i)
                    p[j/32]&=~(1<<j%32);
    }
    int main()
    {
        clock_t start=clock();
        unsigned int *p=(unsigned int*)malloc(12500000);
        /*一亿个数只要用12500000个字节表示,每个字节8位.按一个整数32位计算,
        只要12500000/4个整数型就可以表示
        */
        if(!p){
            cout<<"no enough memory."<<endl;
            return 1;
        }
        memset(p,255,12500000);
        sieve(p);
        int sum=-2;
        for(int i=0;i<12500000/4;++i)
            sum+=_count(p[i]);
        free(p);
        printf("%d,%7.3f
    ",sum,(clock()-start)/CLK_TCK);
        return 0;
    }
    
  • 相关阅读:
    Chap5:操作文件和目录[The Linux Command Line]
    ABC3
    ABC2
    ABC
    Spring MVC / Boot
    Usefull Resources
    [ Learning ] Design Pattens
    [ Learning ] Spring Resources
    URL Resources
    [ Windows BAT Script ] BAT 脚本获取windows权限
  • 原文地址:https://www.cnblogs.com/vactor/p/4346905.html
Copyright © 2011-2022 走看看