Java bootcamp · Lab 29

Collatz steps

mediumWhile12 minLesson: While

Read the question, write Java on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Collatz steps from n to 1.

Examples

Example 1
Input
6
Output
8
Example 2
Input
1
Output
0
Hint
  1. even: n/=2; odd: n=3*n+1
Show correct code

Peek only after you have tried. You can still Check your own version.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int steps = 0;
    while (n != 1) {
      n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
      steps++;
    }
    System.out.println(steps);
  }
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.