[ACM] 3n+1

太久沒有寫code了 , 想說來寫寫練習一下 , 剛好看到有人的3n+1的code , 想說來寫個比較簡短的版本 , 直接recursive 下去做真的是方便時很多呢!

BTW , 我發現我真的很愛用三元運算子= =” , 清楚又短~


#include <stdio.h>
void cal(int,int);
int m_cal(int,int);
int main (int argc, const char * argv[]) {
int input1,input2;
while(scanf("%d%d",&input1,&input2)!=-1){
cal(input1,input2);
}
return 0;
}
int m_cal(int a,int length){
if(a==1){
return length;
}else if(a%2==1){
return m_cal(a*3+1,length+1);
}else{
return m_cal(a/2,length+1);
}
}
void cal(int a,int b){
int i=a>b?b:a,j=a>b?a:b;
int temp,memory=0;
for(i;i<=j;i++){
temp = m_cal(i,1);
memory = temp>memory ? temp:memory;
}
printf("%d %d %dn",a,b,memory);
}

Leave a Reply

Your email address will not be published. Required fields are marked *