Collatz Conjecture with PHP

First, do a search for “Collatz Conjecture” to find out what it is (no need for me to explain it here…)

Although PHP isn’t the fastest language around, it’s extremely popular, and its my language of choice, so I wanted to make a basic program to try and solve this problem in PHP. So far, no results (as to be expected), but interesting to code nonetheless. Here’s what I made:

for ($x = 2; $x >= 1; $x++) {
        if ($x%100000000 == 0){
            echo 'not ' . $x . '<br />';
        $y = 0;
        $i = $x;
        do {    
                if ($y === 999){
                    echo $x . '<br />';
                if ($i % 2 === 0){
                    $i = $i/2;
                } else {
                    $i = 3 * $i + 1;
        } while ($i != 4);

So what did I do here? It starts off with an intentional infinite loop. The for statement runs as long as $x is greater than 1, and since we’re increasing $x on each iteration of the loop, its always true. The next three lines are really just a way to keep track of where the loop is currently up to, its set so that every 100 million iterations, it just says the current number.

Next I set $y = 0, later $y will be incrementing to let me know how many steps are in the current sequence.

Then I set $i = $x, this is just so that we can keep $x in-tact, and not need to change it as we run through the actual sequence

The remainder of the code is a do while loop that will continue looping as long as $i != 4. So keep in mind that this is a loop inside of a loop. I chose to check if $y === 999 because there are barely any (and none that I’ve yet to find) numbers that have a sequence larger than 1000 steps. After checking the number of steps, we have an if statement to do the actual Collatz Conjecture math.

Running this on my local computer, it takes about 30 minutes to search 100 million numbers. Again, PHP isn’t the fastest language around, and if you seriously wanted to find a number that didn’t match the 4-2-1 sequence, you would probably want to do this is C

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>