我正在尝试在http://www.programming-challenges.com提交我的代码,但我只得到错误的答案。我已经尝试了1000000这样的大输入数字来测试,我的代码返回了答案。如果有人可以提供帮助,我会非常感激。无论如何,这是我的代码:
#include <stdio.h>
unsigned int max_cycle(unsigned int i, unsigned int j);
unsigned int cycle_size(unsigned int m);
void swap(unsigned int *m, unsigned int *n);
int main(int argc, char *argv[]) {
unsigned int a, b;
int scan;
scan = scanf("%u %u", &a, &b);
printf("%u %u %u", a, b, max_cycle(a, b));
while (scan> 0) {
if((scan = scanf("%u %u", &a, &b)) > 0) {
printf("\n%u %u %u", a, b, max_cycle(a, b));
}
}
return 0;
}
unsigned int max_cycle(unsigned int x, unsigned int y) {
unsigned int length = 0;
unsigned int max = 0;
if(x > y) {
swap(&x, &y);
}
x++;
while(x < y) {
length = cycle_size(x);
if(length > max) {
max = length;
}
x++;
}
return max;
}
unsigned int cycle_size(unsigned int x) {
unsigned int cntr = 1;
while(x != 1) {
if(x % 2 == 0) {
x = x/2;
} else {
x = 3*x+1;
}
cntr++;
}
return cntr;
}
void swap(unsigned int *x, unsigned int *y) {
unsigned int term = 0;
term = *x;
*x = *y;
*y = term;
}
答案 0 :(得分:0)
您的代码中存在致命错误。你完全忽略了整数溢出。在找到x开始不符合32位的序列之前,您不必长时间搜索。由于具有不适合32位的序列的x很可能会创建一个长周期,因此您可能会错过具有最大周期长度的数字。
64位会更进一步,但不是那么多。
答案 1 :(得分:0)
您的计划的输出缺少最终\n
。取代
int scan;
scan = scanf("%u %u", &a, &b);
printf("%u %u %u", a, b, max_cycle(a, b));
while (scan> 0) {
if((scan = scanf("%u %u", &a, &b)) > 0) {
printf("\n%u %u %u", a, b, max_cycle(a, b));
}
}
与
while (scanf("%u%u", &a, &b) == 2)
printf("%u %u %u\n", a, b, max_cycle(a, b));
解决这个问题。