提交解决方案后,Codechef网站中出现分段错误错误

时间:2018-06-27 06:01:02

标签: c

问题链接-https://www.codechef.com/problems/SINS

解决方案

    #include<stdio.h>
    int main(){
    int a[30] ;
    int test_case_count, count;
    int i=0;
    scanf("%d", &test_case_count);
    count = test_case_count ;
    while(test_case_count != 0)
    {
       scanf("%d %d", &a[i], &a[i+1]) ;
       test_case_count--;
       i++;
       i++;
    }

  i = 0;

  while(count != 0)
  {
    while(a[i] != a[i+1])
    {
      if(a[i] > a[i+1])
         a[i] = a[i] - a[i+1];
      else
         a[i+1] = a[i+1] - a[i];
    }
   //printf("A = %d && B = %d\n", a[i], a[i+1]);
   printf("%d", a[i] + a[i+1] );
   printf("\n") ;
   count--;
   i++;
   i++;
  }

return 0;
}

请原谅您没有一个优雅的解决方案。初学者在这里。任何帮助将不胜感激。 附言-在家用电脑上使用mingw和atom时完美运行

1 个答案:

答案 0 :(得分:0)

您的代码存在的问题是它非常使用large memory来执行。首先,您必须同时结合 reading printing while loops来避免使用array,这会占用大量内存。使用%而不是重复的减法可以帮助您减少程序的运行时间。

在为诸如codechef之类的平台编码时,请确保:-

  1. 使用更少的内存
  2. 最小运行时间即最小循环次数和迭代次数)。

请尝试以下修改的代码:-

#include <stdio.h>
int main()
{
  int a, b;                          // don't need a[].
  int test_case_count;               // you don't need count.
  int i = 0;
  scanf("%d", &test_case_count);
  while (test_case_count != 0)
  {
    scanf("%d%d", &a, &b);
    test_case_count--;

    while (1)
    {
      if (a > b)
      {
        if (a % b)
          a = a % b;
        else
        {
          printf("%d\n", 2 * b);
          break;
        }
      }
      else
      {
        if (b % a)
          b = b % a;
        else
        {
          printf("%d\n", 2 * a);
          break;
        }
      }
    }
  }

  return 0;
}
相关问题