Course of Raku / Addendum 🆕 / Working with data / Numbers and mathematics / Exercises / Collatz steps
Solution: Collatz steps
Here is a possible solution to the task.
Code
my $n = 27;
my $steps = 0;
while $n != 1 {
$n = $n %% 2 ?? $n div 2 !! 3 * $n + 1;
$steps++;
}
say $steps;🦋 You can find the source code in the file collatz.raku.
Output
111Comments
The ternary
?? !!chooses the next value in one expression: halve$nwhen it is even ($n %% 2), otherwise apply3 * $n + 1.27is a famous small case that takes a surprisingly long detour —111steps — before it finally settles at1.