我正在研究C编程任务来实现Eratosthenes的Sieve,而不使用C的平方根函数。下面是我的输出和我的教授输出,我不确定我的代码中有什么导致它是错误的。有任何想法吗?C:使用数组的Eratosthenes筛选
这里的预期输出
Program initiated
1 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 101 103 107 109 113 127 131 137 139 149
151 157 163 167 173 179 181 191 193 197 199 211
223 227 229 233 239 241 251 257 263 269 271 277
281 283 293 307 311 313 317 331 337 347 349 353
359 367 373 379 383 389 397 401 409 419 421 431
433 439 443 449 457 461 463 467 479 487 491 499
503 509 521 523 541 547 557 563 569 571 577 587
593 599 601 607 613 617 619 631 641 643 647 653
659 661 673 677 683 691 701 709 719 727 733 739
743 751 757 761 769 773 787 797 809 811 821 823
827 829 839 853 857 859 863 877 881 883 887
Program terminated
这里是我的输出:
Program initiated
1 37 41 43 47 53 59 61 67 71 73 79
83 89 97 101 103 107 109 113 127 131 137 139
149 151 157 163 167 173 179 181 191 193 197 199
211 223 227 229 233 239 241 251 257 263 269 271
277 281 283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409 419 421
431 433 439 443 449 457 461 463 467 479 487 491
499 503 509 521 523 541 547 557 563 569 571 577
587 593 599 601 607 613 617 619 631 641 643 647
653 659 661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809 811 821
823 827 829 839 853 857 859 863 877 881 883 887
Program terminated
这里是我的代码:
#include <stdio.h>
void zap(int data[], int divisor)
{
for(int i=0;i<900;i++)
{
if(data[i]%divisor==0) // if mod is not 0, 0 out the index.
{
data[i] = 0;
}
}
}
// the display method
void display(int data[])
{
int count = 0; // init counter on the out side
for(int i=0;i<900;i++)
{
if(data[i]>0)// don't print 0s
{
printf("%4d",data[i]);// print the data in a column
count++;// increment count
if(count==12) // print rows and columns
{
count=0; // reset count
printf("\n"); // print new line
}
}
}
if(count<12)// we terminate loop and we now need print a new line
{
printf("\n");
}
}
int main()
{
// start the program, with a message
printf("Program initiated\n");
// needs to be 900 long
int primes[900];
// populate the array
for(int i=1; i <= 900; i++)
{
primes[i] = i;
}
// elminate the bad numbers
for(int i=2; i < 35; i++)
{
zap(primes,i);
}
// display the array.
display(primes);
// print the end message
printf("Program terminated\n");
return 0;
}
只是一个迅速的评论:我不认为你实现了* sieve * - 对于这个算法,你一次只取一个数字,*从你将看的数字列表中移除*号码的倍数在 - 看到没有分裂只涉及乘法和查找 - 你在另一方面使用除法... – Carsten 2012-03-19 05:38:34
我该怎么做? – 2012-03-19 05:40:08
顺便说一句:至于为什么你的versino不工作:请记住,我%i == 0(mod的一切),看看你的“zap”(最多35,其中36 = 3 * 12)的电话...... – Carsten 2012-03-19 05:40:26