I would like to solve problem PRIME1 on SPOJ. When I run Code Blocks and input test examples, I get correct answer. But when I submit my code to SPOj, I get SIGSEGV error. Here is the explanation of this error on SPOJ: SIGSEGV (signal 11) - the most common error for non-interpreted languages: a "segmentation fault" of the program. This may be caused e.g. by an out-of-scope array index causing a buffer overflow, an incorrectly initialized pointer, etc. But I can't find this type of problem in my code. Could anyone help me, please?
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <math.h>
int prim(int n)
{
int s, i;
if (n == 1 || n == 2)
return 1;
if (n % 2 == 0)
return 0;
s = (int)sqrt(n);
for (i=3; i<=s; i+=2)
if (n % i == 0)
return 0;
return 1;
}
void print(int a,int b)
{
int *p,i,k;
int g;
g=(b/2);
p = (int *) malloc (sizeof(int)*(b-a+1));
for(i=0;i<(b-a+1);i++) p[i]=a+i;
for(i=0;i<=g;i++)
{
if(p[i] && prim(p[i]))
{
for(k=i*2+a;k<b-a;k+=i+a)
p[k]=0;
}
if(!prim(p[i]))
{
p[i]=0;
for(k=i*2+a;k<=b-a;k+=i+a)
p[k]=0;
}
}
for(i=0;i<(b-a+1);i++) if(p[i]!=0) printf("%d ",p[i]);
free(p);
}
int main(void)
{
int t,i,m,n;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&m,&n);
print(m,n);
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire