An interesting task offered on Week 54 of the Perl Weekly Challenge:
Print the Collatz Conjecture for the given integer number.
You will see the definition of the Collatz sequence in the code. The conjecture is that for any starting number, the sequence ends with 1.
Here is the definition that is expressed directly in Raku code:
multi sub collatz($n where $n %% 2) { $n / 2 } multi sub collatz($n) { 3 * $n + 1 }
The two multi-functions choose between even and odd numbers.
As we know that the sequence should end with 1, let’s use the sequence operator with the expected final item.
my $start = 23; .say for $start, {collatz($_)} ... 1;
And indeed, that perfectly works:
$ raku ch-054-2.raku 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
Try it with other numbers, for example, 42.