google / google/comprehensive-rust
Minor suggested updates to the Collatz Sequence exercise in section 6.8 and its solution in section 6.8.1
- Dominant language
- Rust
- Stars
- 33.4k
- Forks
- 2.1k
- Avg merge
- 1d 3h
- Merged PRs (30d)
- 10
Description
The first suggestion is that the Collatz Sequence is only valid when `n` is in the set of natural numbers. Thus the input parameter `n` into the `collatz_length` function should be `u32` and not `i32` - especially since the output is `u32` - thus no need for unnecessary casting.
The second suggestion is that I propose a solution that matches the official sequence, which only counts the number of tripling and halving operations. i.e.:
| n | length |
| --- | ------ |
| 1 | 0 |
| 2 | 1 |
| 3 | 7 |
The On-line Encyclopedia of Integer Sequences (OEIS) for the Collatz conjecture, A006577 - "Number of halving and tripling steps to reach 1 in '3x+1' problem, or -1 if 1 is never reached.":
[OEIS - A006577 as a simple table](https://oeis.org/A006577/list).
A possible solution is:
```rust
/// Determine the length of the Collatz sequence.
///
/// We are defining the length of the Collatz sequence as the number of halving
/// and tripling steps to the end of the collatz sequence (n == 1) beginning at
/// `n`. This function will just return `0` for the invalid input `n == 0`
/// instead of returning an error as we have not yet covered that in this
/// course.
///
/// More info: https://en.wikipedia.org/wiki/Collatz_conjecture
/// This follows the pattern from: https://oeis.org/A006577/list
pub fn collatz_length(mut n: u32) -> u32 {
let mut counter = 0_u32;
while n > 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
counter += 1;
}
counter
}
#[test]
fn test_collatz_length() {
assert_eq!(collatz_length(0), 0);
assert_eq!(collatz_length(1), 0);
assert_eq!(collatz_length(2), 1);
assert_eq!(collatz_length(11), 14);
assert_eq!(collatz_length(27), 111);
assert_eq!(collatz_length(837799), 524);
}
fn main() {
println!("Length: {}", collatz_length(11));
}
```
Contributor guide
Assessment
This issue has not been assessed yet.