解答

  1. /// Determine the length of the collatz sequence beginning at `n`.
  2. fn collatz_length(mut n: i32) -> u32 {
  3. let mut len = 1;
  4. while n > 1 {
  5. n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
  6. len += 1;
  7. }
  8. len
  9. }
  10. #[test]
  11. fn test_collatz_length() {
  12. assert_eq!(collatz_length(11), 15);
  13. }
  14. fn main() {
  15. println!("Length: {}", collatz_length(11));
  16. }