用篩選法可得到2~n(n<10000)之間的所有素數,方法是:首先從素數2開始,將所有2的倍數的數從數表中刪去(把數表中相應位置的值置成0);接着從數表中找出下一個非0數,並從數表中刪去該倍數的所有倍數; 以此類推,直到所找到的下一個數等於n為止。這樣會得到一個序列:2,3,5,7,11,13,17,19,23...
#include <stdio.h>
int fun(int n)
{ int a[10000], i,j, count=0;
for (i=2; i<=n; i++) a[i] = i;
i = 2;
while (i<n) {
/**********found**********/
for (j=a[i]*2; j<=n; j+=a[i])
a[j] = 0;
i++;
/**********found**********/
while (a[i]==0)
i++;
}
printf("\nThe prime number between 2 to %d\n", n);
for (i=2; i<=n; i++)
/**********found**********/
if (a[i]!=0)
{ count++; printf( count%15?"%5d":"\n%5d",a[i]); }
return count;
}
main()
{ int n=20, r;
r = fun(n);
printf("\nThe number of prime is : %d\n", r);
}