Collatz Conjecture in Java: Explanation & Practice

Generate Collatz sequence for a number

Problem summary

Starting from n: if even, divide by 2; if odd, multiply by 3 and add 1. Continue until reaching 1.

Starter code

public class Main {
    public static void main(String[] args) {
        int n = 6; // Test case 1
        
        // Generate Collatz sequence
        // Print each number space-separated ending with 1
    }
}

Expected output and test cases

  • Collatz(6)
    6 3 10 5 16 8 4 2 1
  • Collatz(7)
    7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
  • Collatz(1)
    1

Hints

  1. Use while loop until n becomes 1
  2. Check if n is even with n % 2 == 0
  3. Apply the appropriate rule

Related Control Flow exercises

Practice all Control Flow exercises · Run this idea in the Java compiler