- 论坛徽章:
- 0
|
判断一个数是否是质数,经过实验,即使在2千万的范围内,还是查表的速度更快,占用内存也不多,即使2千万的位序列也不过占2M左右的内存。
写了一个程序,自动生成一个静态表函数。
- #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;
- }
复制代码
比如生成的0-2000范围内的质数表函数(内置位序列,0为false,非0为true,判断质数):
- 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)));
- }
复制代码
[ 本帖最后由 haoji 于 2008-9-22 19:12 编辑 ] |
|