- 論壇徽章:
- 0
|
判斷一個(gè)數(shù)是否是質(zhì)數(shù),經(jīng)過(guò)實(shí)驗(yàn),即使在2千萬(wàn)的范圍內(nèi),還是查表的速度更快,占用內(nèi)存也不多,即使2千萬(wàn)的位序列也不過(guò)占2M左右的內(nèi)存。
寫(xiě)了一個(gè)程序,自動(dòng)生成一個(gè)靜態(tài)表函數(shù)。
- #include <stdio.h>
- #include <stdlib.h>
- #include <limits.h>
- #include <math.h>
- int main(int argc, char** argv)
- {
- int total=2000;
- int cols=6;
- int myjs=1;
-
- if(argc>2)
- {
- fprintf(stderr,"Usage:%s total\n",argv[0]);
- return -1;
- }
- else if(argc==2)
- total=(int)strtol(argv[1],NULL,10);
-
- int js=3;
- int i;
- int t;
- printf("int myadjust(int shu)\n\
- {\n\
- assert(shu<=%d);\n\
- const static unsigned int mytable[]={\n\
- ",total);
- unsigned int output=0x60000000;
- for(t=3;t<=total;t++)
- {
- int k=(int)(sqrt(t));
- if(t%2==0)
- i=0;
- else
- for(i=3;i<=k;i+=2)
- if(t%i==0)
- break;
- if(i>k)
- output|=(0x80000000 >> (js & 0x1F));
-
- if((js & 0x1F) == 31)
- {
- printf("0x%X,",output);
- output=0;
- if(myjs++ % cols ==0)
- printf("\n\
- ");
- }
-
- js++;
- }
- if((--js & 0x1F) != 31)
- printf("0x%X\n",output);
- printf(" };\n\n return (mytable[shu >> 5] & ((unsigned int)0x80000000 >> (shu & 0x1F)));\n}\n");
- return 0;
- }
復(fù)制代碼
比如生成的0-2000范圍內(nèi)的質(zhì)數(shù)表函數(shù)(內(nèi)置位序列,0為false,非0為true,判斷質(zhì)數(shù)):
- int myadjust(int shu)
- {
- assert(shu<=2000);
- const static unsigned int mytable[]={
- 0x75145105,0x4510414,0x11411040,0x45144001,0x10500504,0x11041401,
- 0x45001001,0x14414010,0x41050450,0x4001144,0x104014,0x41010411,
- 0x4044040,0x14014110,0x40451001,0x1101104,0x500004,0x10041050,
- 0x40104141,0x4500100,0x51041400,0x44101004,0x4010104,0x11010440,
- 0x44001004,0x500514,0x1000451,0x45100,0x110100,0x40441040,
- 0x1104101,0x4004414,0x1410050,0x5040001,0x14410404,0x10400001,
- 0x40101004,0x10404004,0x41050400,0x40100005,0x10504510,0x1410000,
- 0x4104,0x4000100,0x40011441,0x1141001,0x514410,0x1001010,
- 0x1044101,0x10110004,0x41441410,0x4000041,0x14000004,0x50040050,
- 0x4041041,0x4114,0x401001,0x1000100,0x4114500,0x40041040,
- 0x140005,0x410,0x10450000
- };
- return (mytable[shu >> 5] & ((unsigned int)0x80000000 >> (shu & 0x1F)));
- }
復(fù)制代碼
[ 本帖最后由 haoji 于 2008-9-22 19:12 編輯 ] |
|