Low-level sieve method for bit processing

Source: Internet
Author: User

I have to say that bit manipulation is a magical thing.

//low-level sieve #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 bit i/32 integer; i%32 is the first /32 integers i%32 bit 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); /* 100 million digits only in 12.5 million bytes, 8 bits per byte. Calculated as an integer 32 bit, as long as the 12500000/4 integer type can represent */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\n", Sum, (Clock ()-start)/clk_tck); return 0;} 

Low-level sieve method for bit processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.