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