您好,我正在嘗試執行hailstone序列。
雹石序列基本上是:取一個給定的整數n - 如果偶數,則序列中的下一個整數是n/2,如果是奇數,則序列中的下一個整數是n * 3 + 1.
API必須遵循對於我的任務,需要使用返回數組列表的方法執行它。
我的問題是代碼只是永遠掛起來,當我在方法本身添加輸出以查看發生了什麼事情時,我發現它總是在由於某種原因給出數字10時掛起。
我希望有一些我可能在我的條件下失蹤的小東西。使用ArrayList的Java中的Hailstone序列
下面是一些示例輸出,當給定n值15時,它會一遍又一遍地輸出。
15是奇數,所以我使它3N + 1:46
46是偶數,所以我除以2:23
23爲奇數,所以我使它3N + 1:70
70是偶數,所以我劃分通過2:35
35是奇數,所以我使它3N + 1:106
106是偶數,所以我除以2:53
53是奇數,所以我使它3N + 1:160
160是即使如此我除以2:80
80即使這樣我除以2:40
40就是這樣我除以2:20
20是偶數,所以我除以2:10
15是奇數,所以我使它3N + 1:46
我的代碼
import java.util.ArrayList;
import java.util.Scanner;
public class HailstoneSequence {
public static ArrayList<Integer> getHailstoneSequence(int n){
ArrayList<Integer> results;
results = new ArrayList<Integer>();
results.add(n);
//while the last number is not 1 perform these actions
while((results.size() - 1) != 1){
//for each number in the array
for(int i=0; i< results.get(i); i++){
//test if odd or even
if((results.get(i)%2)==0){
System.out.println(results.get(i)+" is even so I divide by 2: "+ (results.get(i)/2));
results.add((results.get(i)/2));
}
else{
//odd
System.out.println(results.get(i)+" is odd so I make it 3n+1: "+ (3*(results.get(i))+1));
results.add((3*(results.get(i))+1));
}
}
}
return results;
}
public static void main(String[] args) {
int n=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of n ");
n=sc.nextInt();
sc.close();
//create an initialize new array list to hold results of the hailstonesequence
ArrayList<Integer> list;
list = new ArrayList<Integer>();
list = getHailstoneSequence(n);
//for each number in the array
for(int i=0; i< list.get(i); i++){
if ((list.get(i)!= 1)){
if((list.get(i)%2)==0){
System.out.println(list.get(i)+" is even so I divide by 2: "+ (list.get(i+1)));
}
else{
//odd
System.out.println(list.get(i)+" is odd so I make it 3n+1: "+ (list.get(i+1)));
}
}
else{break;}
}
}
}
也許永遠掛起,因爲這是在算法上做一定的投入呢? –
您是否瀏覽了IDE調試器中的代碼?那是開始的地方。請訪問[help]並閱讀[ask] –
調用'getHailstoneSequence'後for循環的目的是什麼? –