One of the recent reads took me down the mathematics path. This is always a bit of fun. The story was:
I remember the Collatz conjecture from years ago.
Basically, it says to take any number. If the number is even, divide it by two and continue with the result. If the number is odd, then triple it, add one, and continue with the result. The conjecture says that, if you repeat it enough times, you’ll eventually get the number 1.
During dog walks yesterday, I found myself mentally doing the problem. When I didn’t lose track, the sequence of numbers always did end up at 1.
When I got home, I thought; this is silly to do all this mental math. I should write a program.
Here it is in Small Basic. I’ve tried to make it readable and over-commented to explain the steps. I think it should be readable enough.
And, of course, I ran it to make sure that it worked. I played a lot of “kitten on the keyboard” to test it out and sure enough, the answer is always eventually 1.
For simplicity, here are 6 and 7.
Another observation include that, in addition to the answer being 1, any number I tried over 6 ended in the sequence 10 5 16 8 4 2 1. Of course, I didn’t try every number. However, I did modify the original program to loop the original number tested instead of just working with a single input.
After writing the program, I like the programming concepts that it includes.
- Asking the user for input
- Looping until an exit condition is met
- A little mathematics
- A little branching
- Displaying the answer
- Enhancing the original by providing another form of input
- A program doesn’t have to be huge and time consuming to have a lot of concepts
- It’s actually a bit of fun trying to understand the mathematics while doing the coding
There will be a place for something like this in one of your courses or clubs. The puzzle is intriguing because you can run it on a calculator or do it in your mind, in addition to writing a program. It’s nothing so obscure that you can’t get your head around it.
A hugely mathematical explanation of the conjecture can be found here. It doesn’t necessarily make it tougher to understand but it’s a nice confirmation that we don’t have the answers to everything.