Core Beginner

02  Control flow

Loops and conditionals: sum a range, then write the classic fizzbuzz for a single number.

Step 3 / 3

Count Collatz steps in collatz_steps: even goes to n / 2, odd goes to 3n + 1; stop at 1.

Hints
  • while n != 1 { ... } with a step counter.
  • if/else is an expression: n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };.
02_control_flow.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
fn collatz_steps(mut n: u64) -> u32 {
    let mut steps = 0;
    while n != 1 {
        n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
        steps += 1;
    }
    steps
}