c - Eratosthenes 停止筛

标签 c

我正在尝试通过维基百科页面实现埃拉托色尼筛法,但出于某种原因,这段代码停止并且没有完成。我是 C 的初学者,所以如果我误用了任何东西,请解释。

我不确定,但我是否滥用了 sizeof(primes)/sizeof(int)

#include <stdio.h>
#include <malloc.h>

#define bool char
#define false 0
#define true 1

void sieveOfEratosthenes(const int until, int* primes);

int main(int argc, char** argv) {
    puts("sieveOfEratosthenes: 120");
    int* primes = malloc(sizeof(int));
    sieveOfEratosthenes(120, primes);
    for (int i = 0; i < sizeof(primes) / sizeof(int); i++) {
        printf("%d:%d\n", i, primes[i]);
    }
}

void sieveOfEratosthenes(const int until, int* primes) {
    int numbers[until];
    for (int p = 2; p < until; p++) {
        numbers[p] = true;
    }

    int p = 2;
    while (true) {
        for (p = p * p; p < until; p += p) {
            numbers[p] = false;
        }
        for (int count = p; count < until; count++) {
            if (numbers[count] == true) {
                p = count;
                break;
            }
        }
        if (p == until) {
            break;
        }
    }
    int j = 0;
    for (int i = 0; i < until; i++) {
        if (numbers[i] == true) {
            primes = realloc(primes, (j + 1) * sizeof(int));
            primes[j++] = i;
        }
    }
    return;
}

最佳答案

你的套路有几个问题:

void sieveOfEratosthenes(const int until, int* primes) {
    int numbers[until], count;
    for (int p = 2; p < until; p++) {
        numbers[p] = true;
    }

    int p = 2;
    while (true) {
        // You should not overwrite p since you later need it. 
        for (int i = p * p; i < until; i += p) {
            numbers[i] = false;
        }
        for (count = p + 1; count < until; count++) { // p+1 is the next prime candidate
            if (numbers[count] == true) {
                p = count;
                break;
            }
        }
        if (count >= until) {  // You break when the loop above finishes
            break;
        }
    }
    int j = 0;
    for (int i = 2; i < until; i++) {  // 2 is the first prime, not 0
        if (numbers[i] == true) {
            primes = realloc(primes, (j + 1) * sizeof(int));
            primes[j++] = i;
        }
    }
    return;
}

除此之外,sizeof primes 方法不起作用。你将不得不交回从你的例程中找到的素数的数量。

关于c - Eratosthenes 停止筛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22756023/

相关文章:

c - 替换C中字符串中的字符

objective-c - 匿名与定义枚举

c - (作业)将 C 递归函数翻译为汇编(AT&T 语法)

iphone - 如何在iPhone应用程序中通过修改图像的像素值来为UIImage添加色调效果

c - 如何从末尾删除 C 中控制台上打印的当前行?

c - 这段代码是否尽可能高效?

c - 在 STM32H7 上使用执行跟踪片上缓冲区 (ETB)

c - 找到一对数字的4次方等于输入数字

c++ - 在切换到 64 位整数之前,为什么使用 INT_MAX 而不是 UINT_MAX?

c++ - 检索在 svchost 后面运行的服务的名称