Posted By

mscribellito on 10/22/11


Tagged

recursion problem collatz conjecture


Versions (?)

Collatz


 / Published in: PHP
 

  1. <?php
  2.  
  3. $c = new Collatz();
  4.  
  5. echo $c->run(256);
  6.  
  7. echo $c->steps();
  8.  
  9. class Collatz {
  10.  
  11. private $steps;
  12.  
  13. public function __construct() {
  14.  
  15. $this->steps = 0;
  16.  
  17. }
  18.  
  19. public function steps() {
  20.  
  21. return $this->steps;
  22.  
  23. }
  24.  
  25. public function run($n) {
  26.  
  27. $result;
  28.  
  29. if ($n == 1) {
  30.  
  31. $result = 1;
  32.  
  33. } else if ($n % 2 == 0) {
  34.  
  35. $result = $this->run($n / 2);
  36.  
  37. } else {
  38.  
  39. $result = $this->run($n * 3 + 1);
  40.  
  41. }
  42.  
  43. if ($n != 1) $this->steps++;
  44.  
  45. return $result;
  46.  
  47. }
  48.  
  49. }

Report this snippet  

You need to login to post a comment.