我正在尝试编写一个实现 Eratosthenes 筛子的素数生成器。但是,它在输出中包含一些合数(例如 25、49 和其他 5 和 7 的倍数)。
这是我的代码:
/*****
 * To find out prime numbers from 1 to 100 with a different procedure
 * Author:Udit Gupta
 * Date:20/08/2011
 */
#include<stdio.h>
int main() {
    int a[100],i,j,k,n;
    for(i=0;i<=99;i++)
        a[i] = i+1;  /*1 to 100 numbers are entered into array*/
    /*Here te actual logic starts .......*/
    j = 1;
    while ( (a[j] != 0) && (j!=50) ) {
        k = 1;
        n = a[j];
        while( (n * k) < 99) {
            a[j+(n*k)] = 0;
            k++;
        }
        j++;
    }
    /*To print output of the array*/
    for (i=0;i<=99;i++) {
        if ( a[i] != 0)
            printf("\n%d",a[i]);
    }
    return 0;
}
这是输出....
udit@udit-Dabba ~/Desktop/letusc/ch8 $ gcc -o Dd Dd.c -Wall udit@udit-Dabba ~/Desktop/letusc/ch8 $ ./Dd
1 2 3 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 83 85 89 91 95 97