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