ClarkeRubber

The Collatz Conjecture (Graphical Output)

Sep 24th, 2011
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.13 KB | None | 0 0
  1. <?php
  2. function collatz($originalNumber){ //the collatz conjecture function
  3.   $number = $originalNumber;
  4.   do{
  5.   $i++;
  6.       if(1&$number){
  7.         $number = (3*$number)+1;
  8.       }else{
  9.         $number = $number/2;
  10.       }
  11.   }while($number != 1);
  12.   return $i;
  13. }
  14.  
  15. echo "Collatz Conjecture\n"; // :D
  16.  
  17. $n = 1;
  18. do{ //could've used a for loop, but I think this worked out better.
  19.   $i = collatz($n); //testing how many steps that it will take for the number $n to reach 1.
  20.   if($i > $maxheight){ //if the result is larger than all the  rest, the new result will become the largest result.
  21.     $maxheight = $i;
  22.   }
  23.   $x[$n] = $i; //$n is the position along the x-axis, $i is the position along the y-axis.
  24.   $n++; //next number
  25. }while($n < 1000); //find the amount of steps that it takes for numbers 1 to one thousand... which is probably a little high. CHANGE THIS DEPENDING ON HOW MANY NUMBERS YOU WANT TO TEST
  26.  
  27. //---begin writing file
  28. unlink("image.ppm"); //file that we will be editing, we are are deleting the file so we have a clean file to work on
  29. $fh = fopen("image.ppm", 'a+'); //creates the image file that we will be editting and opens the file for appending
  30.  
  31. $width = $n; //width of the image is the largest number that was tested
  32. $height = $maxheight; //height is the largest amount of steps that it took to reach zero
  33.  
  34. $startWrite = "P3\n# image.ppm\n".$width." ".$height."\n255\n"; //fomatting the ppm file
  35. fwrite($fh, $startWrite);
  36.  
  37. $Nl = " ";
  38. for($k = 0; $k < $width*$height; $k++){
  39.   $CurPx = $k%$n; //basic modulus to decide when a new line must be made
  40.   if($CurPx == 0){ //^ditto^
  41.     $CurPy++;
  42.   }
  43.   if($x[$CurPx] == $height-$CurPy){ //basic algebra
  44.     $out = "255"; //if the if statement above reflects the array which was made on line 23, the pixel will be white
  45.   }else{
  46.     $out = "000"; //else, it will be black
  47.   }
  48.   $write = "$out $out $out$Nl"; //the line that is to be outputted
  49.     fwrite($fh, $write); //write the pixel to the file.
  50.     if($CurPx%5 == 0){ //basic formatting decides when a new line must be placed
  51.     $Nl = "\n";
  52.   }else{
  53.     $Nl = " ";
  54.   }
  55. }
  56. fclose($fh); //close the file, done!
  57. ?>
Advertisement
Add Comment
Please, Sign In to add comment