forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollatz_sequence.rs
More file actions
32 lines (30 loc) · 777 Bytes
/
collatz_sequence.rs
File metadata and controls
32 lines (30 loc) · 777 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// collatz conjecture : https://en.wikipedia.org/wiki/Collatz_conjecture
pub fn sequence(mut n: usize) -> Option<Vec<usize>> {
if n == 0 {
return None;
}
let mut list: Vec<usize> = vec![];
while n != 1 {
list.push(n);
if n.is_multiple_of(2) {
n /= 2;
} else {
n = 3 * n + 1;
}
}
list.push(n);
Some(list)
}
#[cfg(test)]
mod tests {
use super::sequence;
#[test]
fn validity_check() {
assert_eq!(sequence(10).unwrap(), [10, 5, 16, 8, 4, 2, 1]);
assert_eq!(
sequence(15).unwrap(),
[15, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1]
);
assert_eq!(sequence(0).unwrap_or_else(|| vec![0]), [0]);
}
}