2007-02-17

【Q100】3n+1 Problem

題目:http://acm.uva.es/p/v1/100.html

  這題基本上沒有太大困難,不過有點小機車處...
For any two numbers i and j you are to determine the maximum cycle length over all numbers between i and j.
  就這關鍵字讓我debug很久,深信自己答案的正確性,卻一直收到WA...差點就給他翻桌了>"<>>>>i和j之間,並不代表i一定恆小於j,所以程式必須要加上這部份的判斷...嘆氣(雙手攤)

程式: http://yaushung.googlepages.com/2007021701.c

內容:

#include <stdio.h>

int q100(int n) ;

int main() {
int i, j, k, sum, temp ;
while(scanf("%d %d", &i, &j) != EOF) {
sum = 0 ;
k= i>j ? j : i ;
for( ; k<=j k<=i; k++) {
temp=q100(k) ;
if(sum < temp)
sum = temp ;
}
printf("%d %d %d\n", i, j, sum) ;
}
return 0 ;
}


int q100(int n) {
int length = 1 ;
while(n != 1) {
length++ ;
if(n % 2)
n = 3 * n + 1 ;
else
n = n / 2 ;
}
return length ;
}

沒有留言: