31 October 2009 ~ 1 Comment

Calculate a hailstone sequence

One of the Project Euler problems deals with the Collatz conjecture, which can basically be summed up like this:

We take any whole number n greater than 0. If n is even, we halve it (n/2), else we do “triple plus one” and get 3n+1. The conjecture is that for all numbers this process converges to 1.

So you start with some seed number (n) and keep moving to the next number in the sequence by either dividing by two or multiplying by three and adding one. If you start with 1, you’d get 1, 4, 2, 1. If you start with 5, you’d get 5, 16, 8, 4, 2, 1. The reason these are also known as “hailstone sequences” is because the numbers rise and sink like ice in an thunderstorm cloud. Every number ever tested has always ended up falling to 1, but it’s never been mathematically proven that every number does the same.

Anyway, here’s some Ruby that, given a seed (n), will yield each number in the sequence and return the total length:

I added a few lines to write the output to a .csv file and then plotted it (n=27) using R:

hailstone27

That’s 112 data points going as high as 9232 before eventually dropping down to 1.

Tags: , , ,

One Response to “Calculate a hailstone sequence”


Leave a Reply