C中哥德巴赫猜想的段断层

C中哥德巴赫猜想的段断层

我的程序在大部分情况下都能正常工作,但每当我试图检查一个大于6576900的数字时,就会出现分段错误。
最奇怪的是,它实际上超过了那个点,如果开始得更早,我只是不能让它超过那个点。
关于这个问题可能存在的地方,以及我可以纠正它的方法,有什么建议吗?

#include <stdio.h>
#include <stdbool.h>
#define TRUE 1
#define FALSE 0

void goldbach(int);

int main(void) {
    int n;

    printf("Enter a number to start testing the goldbach conjecture: ");
    scanf("%i", &n);

    goldbach(n);

    return 0;
}

void goldbach(int n) {
    _Bool goldbachCheck = TRUE;

    //keep running as long as n can be expressed as the sum of two primes
    while(goldbachCheck == TRUE) {
        _Bool isPrime[n];

        for(int i = 2; i < n; i++) {
            isPrime[i] = TRUE;
        }

        //Sieve of Erastosthenes method for calculating all primes < n
        for (int i = 2; i*i < n; i++) {
            if (isPrime[i]) {
                for (int j = i; i*j < n; j++) {
                    isPrime[i*j] = FALSE;
                }
            }
        }

        //counts number of primes found
        int primes = 0;
        for (int i = 2; i < n; i++) {
            if (isPrime[i]) {
                primes++;
            }
        }


//store primes in an array
        int storePrimes[primes];
        int count = 0;
        for (int i = 3; i < n; i++) {
            if (isPrime[i]) {
                storePrimes[count++] = i;
            }
        }

        //Checks if n can be expressed as the sum of two primes
        int start = 0;
        int end = count -1;

        while (start <= end){
            if (storePrimes[start] + storePrimes[end] == n) {
                break;
            }
            else if (storePrimes[start] + storePrimes[end] < n){
                start++;
            }
            else {
                end--;
            }
        }

        if (storePrimes[start] + storePrimes[end] == n) {
            printf("%i = %i + %i\n", n, storePrimes[start], storePrimes[end]);
        }
        else {
            printf("%i can not be expressed as the sum of two odd primes.\n", n);
            goldbachCheck = FALSE;
        }
        //Moves on to next even integer
        n+=2;
    }
}

最佳答案

很可能您遇到了堆栈限制,通常设置为8192k

# ulimit -s
8192

您可以通过指定
# ulimit -s unlimited

如果你在Mac上运行这个,你可以通过运行
# ulimit -a hard

关于c - C中哥德巴赫猜想的段断层,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42239264/

10-11 21:07