解释使用筛选法求100之内的素数
《C程序设计(第五版)》谭浩强著,第六章第165页第1道题
- 用筛选法求100之内的素数。
c
#include <stdio.h>
int main()
{
int i, j, a[101];
for (i=1; i<=100; i=i+1)
{
a[i]=i;
}
printf ("a[0]=%d\n", a[0]);
printf ("a[1]=%d\n", a[1]);
printf ("a[100]=%d\n", a[100]);
printf ("a[101]=%d\n", a[101]);
printf ("注意a[0]是存在的但没有被赋值为0,a[0]的值是未知的,而a[101]是不存在的也没有被赋值,本程序是不使用a[0]和a[101]的");
a[1]=0;
//因为a[1]=1,而1不是素数,把a[1]赋值为0,标记为非素数
printf ("\n");
for (i=1; i<=100; i=i+1)
{
printf ("i=%d a[i]=%d\n", i, a[i]);
for (j=i+1; j<=100; j=j+1)
{
if (a[i]!=0 && a[j]!=0)
{
if (a[j]%a[i]==0)
{
printf ("%d ", a[j]);
a[j]=0;
}
}
}
}
for (i=2; i<=100; i=i+1)
{
if (a[i]!=0)
{
printf ("%d ", a[i]);
}
}
return (0);
}
suozhang@localhost test6_1$ ./test6_1
a0=1269985220
a1=1
a100=100
a101=134514169
注意a0是存在的但没有被赋值为0,a0的值是未知的,而a101是不存在的也没有被赋值,本程序是不使用a0和a101的
i=1 ai=0
i=2 ai=2
4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 i=3 ai=3
9 15 21 27 33 39 45 51 57 63 69 75 81 87 93 99 i=4 ai=0
i=5 ai=5
25 35 55 65 85 95 i=6 ai=0
i=7 ai=7
49 77 91 i=8 ai=0
i=9 ai=0
i=10 ai=0
i=11 ai=11
i=12 ai=0
i=13 ai=13
i=14 ai=0
i=15 ai=0
i=16 ai=0
i=17 ai=17
i=18 ai=0
i=19 ai=19
i=20 ai=0
i=21 ai=0
i=22 ai=0
i=23 ai=23
i=24 ai=0
i=25 ai=0
i=26 ai=0
i=27 ai=0
i=28 ai=0
i=29 ai=29
i=30 ai=0
i=31 ai=31
i=32 ai=0
i=33 ai=0
i=34 ai=0
i=35 ai=0
i=36 ai=0
i=37 ai=37
i=38 ai=0
i=39 ai=0
i=40 ai=0
i=41 ai=41
i=42 ai=0
i=43 ai=43
i=44 ai=0
i=45 ai=0
i=46 ai=0
i=47 ai=47
i=48 ai=0
i=49 ai=0
i=50 ai=0
i=51 ai=0
i=52 ai=0
i=53 ai=53
i=54 ai=0
i=55 ai=0
i=56 ai=0
i=57 ai=0
i=58 ai=0
i=59 ai=59
i=60 ai=0
i=61 ai=61
i=62 ai=0
i=63 ai=0
i=64 ai=0
i=65 ai=0
i=66 ai=0
i=67 ai=67
i=68 ai=0
i=69 ai=0
i=70 ai=0
i=71 ai=71
i=72 ai=0
i=73 ai=73
i=74 ai=0
i=75 ai=0
i=76 ai=0
i=77 ai=0
i=78 ai=0
i=79 ai=79
i=80 ai=0
i=81 ai=0
i=82 ai=0
i=83 ai=83
i=84 ai=0
i=85 ai=0
i=86 ai=0
i=87 ai=0
i=88 ai=0
i=89 ai=89
i=90 ai=0
i=91 ai=0
i=92 ai=0
i=93 ai=0
i=94 ai=0
i=95 ai=0
i=96 ai=0
i=97 ai=97
i=98 ai=0
i=99 ai=0
i=100 ai=0
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
当int a100时,只有a99没有a100,而当int a101时,只有a100=100,没有a101,这时a0和a101都是不用的,它们的值是a0=1269944604 a101=134514009,当循环运行到a100=100时,i=100+1=101,这时循环已经停止了,没有执行下一步a101=101时,i=101+1=102
第一步先int a101;定义101个变量,第一个变量a0是不使用的就不赋值,第二步对这100个变量进行赋值,加工第三步因为a1=1,而1不是素数,把a1赋值为0,标记为非素数,加工第四步数字范围是2-100,以2为分母,再使用2之后的数字范围3-100作为分子除以分母2,能够整除那么余数==0,把分子赋值为0,标记为非素数,如此类推,剩下没有被赋值为0就是素数
ai与aj都是使用同一套数组a1-a100,而不是两套数组
ai作为分母,如果ai=0会产生段错误(核心已转储)