c - 为什么我的 PRIME1 - SPOJ 实现会收到 SIGSEGV,即使它在我的电脑中的所有测试用例中运行良好?

标签 c algorithm primes

输入:

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

这是问题的链接:http://www.spoj.com/problems/PRIME1/

这是我的程序:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
 int n,m,t,i=0,j,k=0;
 int tm[10],tn[10];
 scanf("%d",&t); //test cases
 while(i<t)
 {
  scanf("%d %d", &tm[i],&tn[i]);
  i++;
 } 
 int * a = malloc((n+1)*sizeof(int));

 while(k<t)
    {
     n=tn[k];
     m=tm[k];
     a[0]=a[1]=0;
     for(i=2;i<=n;i++)
        a[i]=i;
     for(i=2;i<=sqrt(n);i++)
     {
        if(a[i])
        {
            for(j=(i*i);j<=n;j+=i)
            {
            a[j]=0;
            }
        }
     } 
     for(i=m;i<=n;i++)
     {
        if(a[i])
            printf("%d \n", a[i]);
     }
     k++;
     printf("\n");
    }
 return 0;
 }

最佳答案

许多编码站点不允许声明大小为 10^9 的数组。这可能会导致 SIGSEGV。

您需要以任何方式更改代码逻辑,因为即使您解决了此错误,您的逻辑也可能会给您带来 TLE

关于c - 为什么我的 PRIME1 - SPOJ 实现会收到 SIGSEGV,即使它在我的电脑中的所有测试用例中运行良好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23161100/

相关文章:

c - 如何更改链表以便删除最后一个链接并替换第一个链接?

algorithm - 在 Delaunay 三角剖分中重新定位点

algorithm - 启发式 - N 是质数吗?

java - 求一个数的因数的方法

c - 基本菜单驱动程序在成功完成第一个任务后重复两次

c - 使用指针作为结构成员将结构序列化为字节数组

c - 为什么 (sizeof(int) > -1) 是假的?

确定一个单词是否可以是英语的算法?

python - 将双峰分布拟合到一组值

c - c 中的 pow() 函数会产生截断(或舍入)错误?