Skip to content

Instantly share code, notes, and snippets.

@Alanaktion
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alanaktion/001cbefbd09bbe3e6aa8 to your computer and use it in GitHub Desktop.
Save Alanaktion/001cbefbd09bbe3e6aa8 to your computer and use it in GitHub Desktop.
Collatz conjecture test
<?php
/**
* Collatz Conjecture Test
*
* This will generate a file showing each step taken to reach 1 following
* the Collatz Conjecture with integers between 2 and 2^20. Note that the
* resulting file will be over 2 GB, so changing pow(2, 20) to a smaller
* number like pow(2, 16) may be preferable.
*
* @author Alan Hardman <alan@phpizza.com>
* @see http://en.wikipedia.org/wiki/Collatz_conjecture
*/
$f = fopen("collatz.txt", "w");
for($i = 2; $i < pow(2, 20); $i++) {
$n = $i;
echo $i, "\n";
while($n != 1) {
fwrite($f, "$i: $n\n");
if($n % 2) {
$n = $n * 3 + 1;
} else {
$n = $n / 2;
}
}
fwrite($f, "$i: 1 SUCCESS\n");
}
fclose($f);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment