Solution
// Copyright 2023 Google LLC // SPDX-License-Identifier: Apache-2.0 /// 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 }
This solution demonstrates a few key Rust features:
mutarguments: Thenargument is declared asmut n. This makes the local variablenmutable within the function scope. It does not affect the caller’s value, as integers areCopytypes passed by value.ifexpressions: Rust’sifis an expression, meaning it produces a value. We assign the result of theif/elseblock directly ton. This is more concise than writingn = ...inside each branch.- Implicit return: The function ends with
len(without a semicolon), which is automatically returned.
- Note that
nmust be strictly greater than 0 for the Collatz sequence to be valid. The function signature takesi32, but the problem description implies positive integers. A more robust implementation might useu32or return anOptionorResultto handle invalid inputs (0 or negative numbers), but panic or infinite loops are potential outcomes here ifn <= 0. - The overflow is a potential issue if
ngrows too large, similar to the Fibonacci exercise.