gpt4 book ai didi

c - SPOJ #2 段错误 (SIGSEGV)

转载 作者:太空宇宙 更新时间:2023-11-04 02:05:43 28 4
gpt4 key购买 nike

我试过了 SPOJ#2 .我只是不知道哪条线是这里的故障问题。试图通过“Eratosthenes 筛法”解决这个问题

#include<stdio.h>
int main()
{

unsigned long long int i,j,LIMIT,NUM1;

// NUM1 and LIMIT are the starting numbers of the range
//like for prime numbers between 31-100 NUM1 = 31 and LIMIT = 100

int *primes;
int z = 1,t;

scanf("%d",&t);
while(t--){

scanf("%lld",&NUM1);
if(NUM1==1)
++NUM1;
scanf("%lld",&LIMIT);

primes = malloc(sizeof(int)*(LIMIT));

for(i=2; i<=LIMIT;i++) //initialise every element by 1
primes[i] = 1;

for (i=2;i<LIMIT;i++)
{
if (primes[i])
for(j=i;j*i<=LIMIT;j++)
primes[i*j]=0; // make 0 all elements that are factor of 'j'
}

for (i=NUM1;i<=LIMIT;i++)
{

if(primes[i])
printf("%d\n",i);
// prime[i] will be one for leftover elements which are prime
}
}
return 0;
}

最佳答案

primes = malloc(sizeof(int)*(LIMIT));

for(i=2; i<=LIMIT;i++) //initialise every element by 1
primes[i] = 1;

错了。您分配了 LIMIT 个整数,它们的索引从 0 到 LIMIT-1。你不能分配给 primes[LIMIT],你的最后一个循环会这样做。替换为

primes = malloc(sizeof(int)*(LIMIT+1));

if (primes==NULL) {
fprintf(stderr, "Can't allocate that much space\n";
exit(1);
}
for(i=2; i<=LIMIT;i++) //initialise every element by 1
primes[i] = 1;

关于c - SPOJ #2 段错误 (SIGSEGV),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20828356/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com