close
題目概要:
給定2個數字,並找出此範圍裡的所有整數3n+1問題需要多少次迴圈才能解得出來,並輸出最大值。Ps 3n+1判別請看原題目。
解題方向:
依題目給的判別方式去判別,並輸出最大值即可。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); | |
} | |
} | |
} |
文章標籤
全站熱搜