4.8 练习:Collatz 序列
练习:Collatz 序列 — Comprehensive Rust
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/control-flow-basics/exercise.html
4.8 练习:Collatz 序列
Collatz 序列 对任意大于零的 n1 定义如下:
- 若 ni 为 1,则序列在 ni 处终止。
- 若 ni 为偶数,则 ni+1 = ni / 2。
- 若 ni 为奇数,则 ni+1 = 3 * ni + 1。
例如,从 n1 = 3 开始:
- 3 是奇数,因此 n2 = 3 * 3 + 1 = 10;
- 10 是偶数,因此 n3 = 10 / 2 = 5;
- 5 是奇数,因此 n4 = 3 * 5 + 1 = 16;
- 16 是偶数,因此 n5 = 16 / 2 = 8;
- 8 是偶数,因此 n6 = 8 / 2 = 4;
- 4 是偶数,因此 n7 = 4 / 2 = 2;
- 2 是偶数,因此 n8 = 1;并且
- 序列终止。
编写一个函数,计算给定初始 n 的 Collatz 序列长度。
1
2
3
4
5
6
7
8
9
10
| // Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
/// 计算从 `n` 开始的 Collatz 序列长度。
fn collatz_length(mut n: i32) -> u32 {
todo!("Implement this")
}
fn main() {
println!("Length: {}", collatz_length(11)); // 应为 15
}
|
01-解答 — Comprehensive Rust