【发布时间】:2011-10-30 23:09:07
【问题描述】:
我正在尝试编写一个实现 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
【问题讨论】:
-
1 不是质数,顺便说一句...
-
您是否尝试过使用调试器
-
你为什么不尝试调试你的代码来找出答案?
-
@MByD:我认为问题是 1、25、35、49、55、65、77、85、91 和 95。
-
@omri 是的,你是对的......我已经应用了逻辑 acc。如果有人能告诉我我做错了什么,我认为是对的?????
标签: c primes sieve-of-eratosthenes number-theory