Skip to main content

Mutliples of 3 and 5

The problem: 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 appears on Project Euler and the solution seems very easy. Maybe it hides some trick or trap but we want to keep the solution and the related implementation as simple as we can!

PHP: a simple iterative cycle


<?php
$sum = 0;
for($i=1; $i < 1000; $i++) {
   $sum = ($i % 3 === 0 || $i % 5 === 0) ? $sum = $sum + $i : $sum;
}
echo $sum;

Python


def getSum():
 sum = 0
 for x in range(1, 1000):
   if x % 3 == 0 or x % 5 == 0:
     sum += x
 return sum
 
# Test
getSum()

Javascript


function getSum() {
   let sum = 0;
   for(let x = 1; x<=1000; x++) {
       if (x % 3 == 0 || x % 5 == 0) {
           sum += x;
       }
   }
   return sum;
}