Bắt đầu ngayBắt đầu miễn phí

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

Bài tập này là một phần của khóa học

Intermediate Java

Xem khóa học

Hướng dẫn bài tập

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

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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");
  }
}
Chỉnh sửa và Chạy Mã