collatz_length/lib.rs
1 /// Returns the length of the Collatz sequence for the given number.
2 /// The Collatz sequence is defined as:
3 /// n -> n/2 (if n is even)
4 /// n -> 3n + 1 (if n is odd)
5 /// The sequence ends when the number is 1.
6pub fn collatz(n: u64) -> u64 {
7 let mut i = n;
8 let mut count = 0;
9 while i != 1 {
10 if i % 2 == 0 {
11 i /= 2;
12 } else {
13 i = i * 3 + 1;
14 }
15 count += 1;
16 }
17 count
18}
19
20#[cfg(test)]
21mod tests {
22 use super::collatz;
23
24 #[test]
25 fn test_20() {
26 assert_eq!(collatz(20), 7);
27 }
28
29 #[test]
30 fn test_1005() {
31 assert_eq!(collatz(1005), 67);
32 }
33
34 #[test]
35 #[ignore]
36 fn test_long() {
37 assert_eq!(collatz(9780657630), 1132);
38 }
39}