BaşlayınÜcretsiz Başlayın

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

Bu egzersiz

Intermediate Java

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

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

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

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");
  }
}
Kodu Düzenle ve Çalıştır