I stumbled across a blog post by Brie Gordon about the Collatz conjecture, so naturally I had to Wikipedia it. The simple story is that for any given integer, if it is even you divide it by 2 and if it is odd you multiply it by 3 and add 1. You continue this pattern with the returned numbers, and eventually the number will reach 1. I’ve heard of it before, but not since one of my earlier computer science classes, so to commemorate the re-discovery I wrote a recursive PHP function to display the progression. Here is the function:
-
function collatz($num)
-
{
-
if($num == 1)
-
{
-
echo "<p style='color: red'>" . $num . "</p>n";
-
return;
-
}
-
-
if($num % 2 == 0) //even
-
{
-
echo "<p style='color: green'>" . $num . "</p>n";
-
return collatz($num / 2);
-
}
-
else
-
{
-
echo "<p style='color: red'>" . $num . "</p>n";
-
return collatz(3 * $num + 1);
-
}
-
}