Project Euler - Problem 1 Solution With PHP

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

It has always been fun for me to play with mathematic problems and when it comes to the mathematics we should check Project Euler.

Here are two solutions I have found for the first problem:

The first option would be like this:

$sum = 0;

for ($i = 0; $i < 1000; $i++) { 

    if ($i % 3 == 0) 
    {
        $sum += $i;
        continue;
    }

    if ($i % 5 == 0) 
    {
        $sum += $i;
    }
}

echo $sum;

For every number which is lower than a thousand we check if this given number divisible to 3 or 5.

The point here is not to use the else statement.

PHP provides a continue statement to skip the remaining part of the current loop. In our case, if the given number is divisible by 3 we skip the second if statement.

And the second option would be like this:

$sum = 0;

for ($i = 0; $i < 1000; $i++) { 

    foreach ([3, 5] as $divisor) 
    {
        if ($i % $divisor == 0) 
        {
            $sum += $i;
            break;
        }
    }
}

echo $sum;

We provide the numbers to be the divisor as a variable. ($number) While we count from 0 to 1000. We check for every divisor and if it divisible by the given $number we are good to break the foreach loop which will let us skip the next numbers in the queue.

Execution time: 0.0009s (both ways)

Copyright © Ozan Kurt 2015.

Scroll to Top