You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
A possible solution is:
/// 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/listpubfncollatz_length(mutn:u32) -> u32{letmut counter = 0_u32;while n > 1{
n = if n % 2 == 0{ n / 2}else{3* n + 1};
counter += 1;}
counter
}#[test]fntest_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);}fnmain(){println!("Length: {}", collatz_length(11));}
The text was updated successfully, but these errors were encountered:
The first suggestion is that the Collatz Sequence is only valid when
n
is in the set of natural numbers. Thus the input parametern
into thecollatz_length
function should beu32
and noti32
- especially since the output isu32
- 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.:
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.
A possible solution is:
The text was updated successfully, but these errors were encountered: