IniziaInizia gratis

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).

Questo esercizio fa parte del corso

Intermediate Java

Visualizza il corso

Istruzioni dell'esercizio

  • 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.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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. All non-even integers are odd
      ____ {
        System.out.println(" is odd");
        n = n * 3 + 1;
      }
      System.out.print(n);
      i += 1;
    }
    System.out.println(" reached in " + i + " steps");
  }
}
Modifica ed esegui il codice