Get startedGet started for free

Collatz

A fun little fact of mathematics is that simple rules can give rise to big consequences. For example, the Collatz Conjecture asks whether two simple rules can reduce any integer to 1.
Its statement is usually the following :

  • For even numbers, halve by 2
  • For odd numbers, multiply by 3, then add 1
    Let's test it out !

Note: If you experience code timeouts, carefully check the logic of the if-else statement (or the Hint).

This exercise is part of the course

Intermediate Java

View Course

Exercise instructions

  • Enter the appropriate termination condition.
  • Call a method to check if n is even.
  • Handle the odd case correctly - this should only trigger if the original n is odd.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

class Collatz {
  static boolean isEven(int n) {
    return n % 2 == 0;
  }
  
  public static void main(String[] args) {
    int n = 1634;
    int i = 0;
    System.out.print(n);
    // Enter the appropriate termination condition
    while (____) {
      // Call a method to check if n is even
      if (____(n)) {
        System.out.println(" is even");
        n /= 2;
      } // Handle the odd case correctly
      ____ {
        System.out.println(" is odd");
        n = n * 3 + 1;
      }
      System.out.print(n);
      i += 1;
    }
    System.out.println(" reached in " + i + " steps");
  }
}
Edit and Run Code