另一个“为什么我的Uva 3n + 1解决方案不被接受?”题

时间:2011-07-22 22:51:34

标签: c ansi

为什么我的解决方案失败了?

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=36

我是在假设stdin是数据来源的情况下写的。

我完全相信这是我的代码的问题,但我很遗憾为什么我得到'错误的答案'作为结果。 (编译器选择是ANSI C)

编辑:修改为允许参数1> param 2(但现在我得到“演示错误”无论是什么)

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[])
{
  unsigned int p1;
  unsigned int start;
  unsigned int end;
  unsigned int current;
  unsigned int n;
  unsigned int p2;
  unsigned int max_cycle = 0;
  unsigned int current_cycle;

  while(scanf("%u %u", &p1, &p2) != EOF){
    max_cycle = 0;
    start = (p1 < p2 ? p1 : p2);
    end = (p1 < p2 ? p2 : p1);
    current = start;
    while(current <= end){
        n = current;
        current_cycle = 0;
        while(n > 1) {
          if(n & 1)
            n = 3*n+1;
          else
            n = n/2;
          current_cycle++;
        }
        current_cycle++;
        if (max_cycle < current_cycle) max_cycle = current_cycle;
        current++;
    }
    fprintf(stdout, "%u %u %u\n", p1, p2, max_cycle );
  }
  return 0;
}

1 个答案:

答案 0 :(得分:1)

if (start == 0 || end == 0) continue;是不必要的,结束条件是两者都为零所以它应该是if (start == 0 && end == 0) break;同样返回0并使它成为int main()(至少在ANSI CI中知道你是否不返回0无论如何都是错的。你也假设我&lt; j并非总是如此(据我记得)。祝你好运。