The Sieve method to calculate the prime must first establish the sieve, here uses the array as the sieve. The subscript corresponds to the number, the corresponding subscript variable's value flag is in the sieve: for 1 in the sieve, for. The expression has been sifted out, not in the sieve. Then look for each round to filter the seed, and the seed is the next smallest prime number after a round of screening, with an initial value of 2.
Filter the seeds for each round and sift through all their multiples, that is, the value of the corresponding subscript variable is assigned to O. The initial multiples are twice times that of the filtered seeds.
The filter is complete, and the remainder of the sieve is prime.
The procedure is as follows:
/*程序8—14,筛法求2至1000之间的所有素数*/
main()
{
int a[1000];/*筛子数组*/
int i;
int minp,double;/*minp筛选种子,double倍数*/
int n=O;/*素数个数,用于输出格式控制*/
for(i=2;i<1000;i++)/*建立筛子*/
a[i]=1;
minp=2;/*筛选种子初始化*/
while(minp<500)/*完成整个筛选*/
{double=2*minp;/*倍数初始化*/
while(double<1000)/*完成一轮筛选*/
{a[double]=O;/*筛去当前倍数*/
double+=minp;/*计算下一个倍数*/
}
do/*计算下一轮筛选种子*/
{minp++;}
while(a[minp]==0);
}
printf("2至1000之间的所有素数如下:\n");
for(i=2;i<1000;i++)
if(a[i]==1)
{printf("%6d",i);
n++;
if(n%5==0)printf("\n");/*5个素数输出在一行*/
}
}