PHP and Numbers Divisible by Three

16 06 2010

The recent technical test also had a fun sort of question in which one needs to write some code to generate a number sequence between 1 and 100 such that all the numbers are divisible by 3. To make things even more fun you had to answer within around 4 minutes. The question itself is not hard and there were several ways I might have answered it.

One way is to use a loop to increment a variable $i and test it on each iteration with a modulus operator to see if there is any remainder. If not, then $i constitutes an integer which displays, as follows:

<?php
for ($i=3, $max=99; $i <= $max; $i++){

    if (($i % 3) == 0) {
        echo $i;
    }
}

I could have set $i to 1 and $max to 100 but these integers lack a clean divisibility by 3, so I saved a little time by using the nearest integers in each case to specify the start and end of the numerical range.

An alternative to the above with its incrementing $i on each iteration would be to use the range() and a foreach loop as follows:

<?php
$nums = range(3,99);
foreach ($nums as $num){
   if (($num % 3) == 0) {
       echo $num;
   }
}

Of course, if you’re using PHP5, you can actually forget testing iteratively whether $num is divisible by 3 as we did in the previous two examples. Instead you can use range() with the optional 3rd parameter indicating the step, as follows:

<?php
foreach ( range(3, 99, 3) as $divBy3) {
   echo $divBy3;
}

Modern PHP may further help speed up accomplishing this task by eliminating the necessity of an array completely. Consider the following script:

<?php
function rangeOfThrees($start, $limit, $step = 3) {
    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
}

foreach (rangeOfThrees(3, 99) as $number) {
     echo "$number\n";
}

See live code.

It makes use of a generator to produce the values divisible by three. As each one gets produced, the loop displays it. Note, this script does not hold the generated values in any sort of an array which conserves memory and thus enhances the speed of execution.

Sometimes you might only be interested in whether a certain number is divisible by three, a problem that can be easily solved by addition oddly enough. It so happens that there is a math rule according to which if the digits of a number add up to three or a multiple of three, then that number is perfectly divisible by three. The following code embodies that rule:

<?php
function is_divisible_by_3($n)
{
    $digits = str_split($n);
    $total = 0;

    foreach ($digits as $digit) {
        $total += $digit;
    }

    if ($total == 3 || ($total % 3 == 0) ){
        return true;
    }

    return false;
}

$num = 110001;

if (is_divisible_by_3($num)){
    echo $num, " is divisible by three. ";
}

See live code.

In this case, $n only requires simple addition to determine if it is wholly divisible by three, following the aforementioned rule of adding the digits of $n. Remarkably str_split() is capable even of splitting an integer into its composite digits.

According to this article there is yet another way to determine if a number may be evenly divided by three. It claims that as long as a number consists of three sequential digits, then you may assume that the number is a multiple of three. Let’s test this notion with some code:

<?php

function isDivisible_x_3($n)
{
  if (strlen($n) == 3){
    list($a,$b,$c) = str_split($n);
    if ($b == $a + 1 && $c == $b + 1){
        $mess =  "\n$n is divisible by three\n";
        $mess .= "\nProof: \$n/3 == " . $n/3;
        return $mess;
    }
  }
}
$num = 234;
echo isDivisible_x_3( $num );

/* 
 */ 

See live code.

The function str_split() again provides a handy way to obtain a number’s digits. Instead of summing the digits, the technique in this example focuses on verifying that the digits consist of only three and are sequential.

This work is licensed under a

Creative Commons License

.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: