Search code examples
javaarraylistcollatz

Collatz conjeceture for each number that is between the two given numbers


num = Integer.parseInt(tf1.getText());
entered = Integer.parseInt(tf1.getText());
num2 = Integer.parseInt(tf2.getText());
entered2 = Integer.parseInt(tf2.getText());

for (i =(int) num; i<= num2 ; i++){ 

    for (j=0 ; j >= i ; j++) {} 

    System.out.println(i);
}

do i have to use array list ? ArrayList<Integer> lists = new ArrayList<Integer>();

and if i use it how i can to separate each number in the arraylist,so I found the numbers between two numbers but how I can take each number and do the collatz conjecture java , please i need help quickly


Solution

  • The collatz conjecture is simple n = n/2 if n%2 == 0 and n = 3*n + 1 if n%2 == 1 and you're doing these calculations until n = 1. Based on this, you could write your function like this:

    public static List<Integer> calculateConjecture(int number) {
        List<Integer> values = new ArrayList<>();
    
        while (number != 1) {
            if (number % 2 == 0) {
                number = number / 2;
            } else {
                number = 3 * number + 1;
            }
            values.add(number);
        }
    
        return values;
    }
    
    public static void main(String[] args) {
        int inferiorLimit = 11;
        int superiorLimit = 15;
    
        for (int i = inferiorLimit; i <= superiorLimit; i++) {
            System.out.println(calculateConjecture(i));
        }
    
    }
    

    The values ArrayList will hold the sequence of numbers for the current number between the [inferiorLimit,superiorLimit]