Project Euler Homework
|
00001 00003 #ifndef _INCL_PRIMETABLE 00004 #define _INCL_PRIMETABLE 00005 const unsigned prime_max = 1000; 00006 class prime_table 00007 { 00008 bool x[prime_max]; 00009 public: 00010 prime_table(); 00011 bool has(unsigned); 00012 unsigned next(unsigned); 00013 }; 00014 00015 prime_table::prime_table() 00016 { 00017 //assume all except 0,1 are prime 00018 x[0]=x[1]=0; 00019 for (bool* p=x+2;p-x<prime_max;p++)*p=1; 00020 00021 for (unsigned n = 2; n < prime_max;n = next(n)) { 00022 unsigned idx=n+n; 00023 while (idx < prime_max) { 00024 x[idx]=0; 00025 idx+=n; 00026 } 00027 } 00028 } 00029 00030 unsigned prime_table::next(unsigned n) 00031 { 00032 if (n>=prime_max)return prime_max; 00033 bool* p = x+n; 00034 do { 00035 p++; 00036 if (*p)return (p-x); 00037 } while (p-x < prime_max); 00038 return prime_max; 00039 } 00040 00041 bool prime_table::has(unsigned k) 00042 { 00043 return x[k]; 00044 } 00045 #endif