Collatz code
Almost 2 years ago - I remembered about a puzzle my maths teacher gave us. It went something like this:
"Start with any positive number. If it's an even number, divide that number by two. If it's odd, multiply your number by three and add one. Then repeat with the number you have.
"Continue," he said. "And you will likely always return to one."
I started with 72. Dividing that by 2, I got 36, then 18, then 9. I multiplied 9 by 3 to get 27, and added 1. 28 is even, so that becomes 14, then 7. 7 multiplied by 3 and add 1, is 22, which can be divided to 11. Then there was 34, 17, 52, 26, 13 before things seem to get there. 13 transforms to 40, which can be divided by 2 to give 20. Then 10. Then 5.
At this point, I wondered where we were going next.
Well, the next number was 16, a power of two. Then 8, 4, 2, 1.
Ta dah!
After I'd remembered this fun, number game I wanted to learn more about it. A quick Google search yielded that it was called the Colatz conjecture and that it's unsolved. You may have spotted that my maths teacher said that you will "likely return to one", with any number you pick. He said "likely" because no one has proven if that is the case.
I discovered that people have used computers to show that all numbers up to a ludicrously large number follow this pattern: but that is not enough to prove that the pattern must work for all numbers.
That got me thinking that maybe I could write a quick-and-dirty Python program (available on GitHub) to calculate the number of steps each value up to N takes to get to 1. So I did that. My code takes a .csv file containing a range of values which will go into the Colatz code as input. And it returns a .csv file with the same inputs next to a count of the number of steps it took to get to 1.
I could use this output to draw a pretty chart showing the number of steps each input value takes to get to 1.
A pretty chart showing the number of steps each input number up to 1,000 (I wasn't very ambitious!) takes to return to 1. |
I obviously haven't proved anything, other than to myself, that hobbyist coding is fun and creates nice patterns sometimes.
I enjoy having these little project swimming around in my head, perhaps placed on the back burner for months. Recently I've started thinking about the Collatz conjecture again - and that I'd like to write more (efficient) Python code to find more patterns.
Comments