【发布时间】:2017-04-04 20:30:47
【问题描述】:
我正在编写一个程序来查找直到 1000 的素数,使用 Eratosthenes 筛......但它不起作用......这是我的整个代码,但是“计算”找到素数在函数“markPrimes”内(我有信心说其余的代码没问题,所以我很确定问题出在这个函数中......
#include <stdio.h>
#include <stdlib.h>
typedef struct primal
{
int number; /* a number */
char mark; /* flag marking the number as active (1) or inactive (0) */
} primal;
void initialize(primal *s,int size)
{
int i;
for(i=0;i<1000;i++)
{
s[i].number=i+1;
s[i].mark=1; //1=prime number
}
}
void markPrimes(primal *s,int size)
{
/* add this function - it should mark all of the numbers in the passed primal array that are not prime numbers as inactive */
//Brute Sieve of Eratosthenes Approach (0=not prime number)
s[0].mark=0; //s[0].number=1 as on the function "initialize" I start from 1 not from 0
int i,j;
for (unsigned i = 2; i*i <size; i++)
{
if (s[i].mark == 1)
for (unsigned j = i<<1;j<size;j+=i)
s[j].mark = 0;
}
}
int main(void)
{
int i,j,prime_numbers[200];
primal source_numbers[1000]; /* an array of source values */
for(i=0;i<200;i++) prime_numbers[i]=0; /* initialize the prime numbers array to 0 */
initialize(source_numbers,1000); /* initialize the source numbers array to hold the numbers 1-1000 */
markPrimes(source_numbers,1000); /* identify the prime numbers in the source numbers array */
/* copy the primes from the source numbers to the prime numbers array */
for(i=0,j=0;i<1000;i++)
{
if(source_numbers[i].mark==1) /* if the current source number is a prime */
{
prime_numbers[j]=source_numbers[i].number; /* copy the number */
j++; /* increment the target index */
}
}
/* print the prime numbers */
for(i=0,j=0;prime_numbers[i]!=0;i++,j++)
{
printf("%3d ",prime_numbers[i]);
if(j==9) /* periodically print a newline and then reset j */
{
printf("\n");
j=-1;
}
}
return 0;
}
【问题讨论】:
-
请更具体。你所说的“它不起作用”是什么意思?你的问题到底是什么?见How to create a Minimal, Complete, and Verifiable example。
-
您可以通过不使用结构而使用
char或bool的简单数组来简化事情。通过检查数组的元素 N 可以找到 N 的素数。您可以将 0 和 1 保留在数组中,因为删除它们比较困难,而且浪费的空间可以忽略不计。