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