Counting the number of letters in a number in binary using PHP

This code is inspired by Matt’s recommendation to “double check” in this video: https://youtu.be/LYKn0yUTIU4?t=4m43s

<?php
$limit = 1000000; // this is the only thing you'll want to change, this is the highest number we'll check against


$eighteen = 0;
$thirteen = 0;
$i = 0;
while ($i < $limit){
    $i++;
    $currentStop = countLetters($i);
    if ($currentStop == 18){
        $eighteen++;
    } else if ($currentStop == 13){
        $thirteen++;
    } else {
        echo 'ERROR!' . $currentStop;
    }
}
echo '18=' . $eighteen .' Which represents ' . 100*($eighteen/$limit) . '% of the total';
echo '<br />';
echo '13=' . $thirteen .' Which represents ' . 100*($thirteen/$limit) . '% of the total';
echo '<br />';


function countLetters($n){
    $ints = str_split (decbin ($n));
    $charCount = 0;
    foreach ($ints as $int){
        if ($int == 0){
            $charCount = $charCount + 4; // "zero" has 4 letters
        } else {
            $charCount = $charCount + 3; // "one" has 3 letters
        }
    }
    if ($n == $charCount){
        return $charCount;
    } else {
        return countLetters($charCount);
    }
}
?>

Running this code will result in the following message:

18=999904 Which represents 99.9904% of the total
13=96 Which represents 0.0096% of the total

Which confirms that Matt is correct.

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>