*This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)*

Task #2 this week was one of my devising:

It is thought that the following sequence will always reach 1:

\(Collatz(n) = \begin{cases}

n \div 2 & n \text{ is even} \\

3n + 1 & n \text{ is odd}

\end{cases}

\)

For example, if we start at **23**, we get the following sequence:

23 → 70 → 35 → 106 → 53 → 160 → 80 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

Write a function that finds the Collatz sequence for any positive integer. Notice how the sequence itself may go far above the original starting number.

## Extra Credit

Have your script calculate the sequence length for *all* starting numbers up to 1000000 (1e6), and output the starting number and sequence length for the longest 20 sequences.

I’ve always liked the Collatz conjecture. It is simple enough for schoolchildren to play with, yet the math to prove the conjecture is still beyond our greatest mathematicians.

Here is how I solved this task.

Continue reading “PWC 054 › Collatz Conjecture”