0
我的程序的目的是找到用戶輸入指示的主要部分。我設置了一個數組來存儲素數,因爲它發現它們。當p(被測整數)遞增並且測試重新開始時,處理通過僅除以數組內的元素而被保存。它直到第44030年的黃金時段效果很好。我正在使用GCC進行編譯。爲什麼它給我一個分段錯誤?條件下的分段錯誤
//Prime Finder
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=4;
int p=7;
int j=1;
int cap;
printf("\nWhich prime number would you like to see? ");
scanf("%i",&cap);
long *array=malloc(cap);
array[0]=1;
array[1]=2;
array[2]=3;
array[3]=5;
while(i<=cap)
{
if (array[j]>=p/2) // if true then p is prime
{
j=1;
array[i]=p;
p++;
i++;
}
else if (p%array[j]==0) // if true then p is not prime
{
p++;
j=1;
}
else // in this case p is still under test
j++;
}
printf("\nHere it is! %i\n\n",array[cap]);
return 0;
}
特定的質數是否可能超過int的存儲長度? (不受任何知識的阻礙) – SchmitzIT
我不這麼認爲。詮釋是不錯的達2,147,483,647。 44030th prime是532691. – bobweek
好吧,別擔心。只是一個想法:) – SchmitzIT