Hello I am attempting to perform the hailstone sequence.
A hailstone sequence is basically: take a given integer n - if even, the next integer in the sequence is n/2, if odd, the next integer in sequence is n * 3 + 1.
The API I must follow for my assignment requires it to be performed as it is with a method returning an arraylist.
My problem is the code just hangs forever, when I added output in the method itself to see what was happening I see it always hangs when it is given the number 10 for some reason.
I am hoping that there is something small I am missing here perhaps in my conditions.
Here is some sample output when given n value of 15 it outputs this over and over again.
15 is odd so I make it 3n+1: 46
46 is even so I divide by 2: 23
23 is odd so I make it 3n+1: 70
70 is even so I divide by 2: 35
35 is odd so I make it 3n+1: 106
106 is even so I divide by 2: 53
53 is odd so I make it 3n+1: 160
160 is even so I divide by 2: 80
80 is even so I divide by 2: 40
40 is even so I divide by 2: 20
20 is even so I divide by 2: 10
15 is odd so I make it 3n+1: 46
My code
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;}
}
}
}