有幾點要考慮:
- 讀取的行數不是單行
- 每行的兩個數值,不一定是前小後大
#include <stdio.h> int cycleLength(int number); int main() { int i, j, input1, input2; while( scanf("%d %d",&input1, &input2) != EOF ){ //檢查與調整前後大小 if(input1 < input2){ i = input1; j = input2; }else{ i = input2; j = input1; } int maxCycleLength = 0; long int x; for ( x = i; x <=j ; x++){ int c = cycleLength(x) ; if (c > maxCycleLength){ maxCycleLength = c ; } } printf("%d %d %d\n",input1,input2, maxCycleLength ); } return 0; } int cycleLength(int number) { int c = 1; while(number!=1){ if(number%2==1){ number = 3*number +1; c++; }else{ number = number/2; c++; } } return c; }
解了此題,但是速度太慢(run time:0.612),要嘗試用別種方法
沒有留言:
張貼留言