Recursive Collatz conjecture in PHP

May 18th, 2010

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:

  1. function collatz($num)
  2. {
  3.     if($num == 1)
  4.     {
  5.         echo "<p style='color: red'>" . $num . "</p>n";
  6.         return;
  7.     }
  8.  
  9.     if($num % 2 == 0) //even
  10.     {
  11.         echo "<p style='color: green'>" . $num . "</p>n";
  12.         return collatz($num / 2);
  13.     }
  14.     else
  15.     {
  16.         echo "<p style='color: red'>" . $num . "</p>n";
  17.         return collatz(3 * $num + 1);
  18.     }
  19. }

View Demo

Leave a Reply