close

題目概要:

給定2個數字,並找出此範圍裡的所有整數3n+1問題需要多少次迴圈才能解得出來,並輸出最大值。Ps 3n+1判別請看原題目。

解題方向:

依題目給的判別方式去判別,並輸出最大值即可。

程式碼:

//Java
import java.util.Scanner;
class uva100{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
int a=sc.nextInt(),b=sc.nextInt();
int min=Math.min(a,b);
int max=Math.max(a,b);
int c=0; //3n+1 所需要迴圈次數的最大值
for(int i=min;i<=max;i++){
int temp=1; //3n+1 所需要迴圈次數
for(int j=i;j!=1;){
if(j%2==0)j=j/2;
else j=j*3+1;
temp++;
}
if(temp>c)c=temp; //判別此數的迴圈次數是否為最大值
}
//Output
System.out.println(a+" "+b+" "+c);
}
}
}
view raw uva100.java hosted with ❤ by GitHub

arrow
arrow
    文章標籤
    Java
    全站熱搜
    創作者介紹
    創作者 a7069810 的頭像
    a7069810

    紀錄自己的程式人生

    a7069810 發表在 痞客邦 留言(0) 人氣()