1
我的程序大部分工作正常,但任何時候我嘗試檢查一個> 6,576,900的數字,我都會遇到分段錯誤。C哥德巴赫猜想中的Seg故障
最奇怪的部分是,如果開始時間較早,它實際上已經超過了那一點,我無法讓它開始過去那一點。
關於問題可能出在哪裏的任何提示,以及我可以改正的方法?
#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;
}
}
段錯誤被拋出在哪裏? – Carcigenicate
任何時候我嘗試輸入一個> 6579000的數字。例如6580000.我得到一個分段錯誤(核心轉儲)輸出。 –
但是哪一行代碼導致段錯誤?你有沒有試過用調試器附加? – Irisshpunk