Solution

/// Determine the length of the collatz sequence beginning at `n`.
fn collatz_length(mut n: i32) -> u32 {
    let mut len = 1;
    while n > 1 {
        n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
        len += 1;
    }
    len
}

fn main() {
    println!("Length: {}", collatz_length(11)); // should be 15
}
  • Note that the argument n is marked as mut, allowing you to change the value of n in the function. Like variables, function arguments are immutable by default and you must add mut if you want to modify their value. This does not affect how the function is called or how the argument is passed in.