I’m given a number and I need to find the sum of the multiples of 3 and 5 below the number. For example: 20 => 78 = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
My code works, but not for numbers greater than 1,000,000 (I tested it for 100,000 – it gives the result with 2sec delay). So, it should be optimized. Could someone help me? Why is my code slow? Thanks.
My logic is as follows:
- add multiples to an array
- filter duplicate values
- sum all values
my code:
function sumOfMultiples(number) { let numberBelow = number - 1; let numberOfThrees = Math.floor(numberBelow / 3); let numberOfFives = Math.floor(numberBelow / 5); let multiples = []; let multipleOfThree = 0; let multipleOfFive = 0; for (var i = 0; i < numberOfThrees; i++) { multiples.push(multipleOfThree += 3); } for (var j = 0; j < numberOfFives; j++) { multiples.push(multipleOfFive += 5); } return multiples .filter((item, index) => multiples.indexOf(item) === index) .reduce((a, b) => a + b); }
Advertisement
Answer
You can just run a loop from 1
to number
, and use the modulo operator %
to check if i
divides 3
or 5
:
function sumOfMultiples(number) { var result = 0; for (var i = 0; i < number; i++) { if (i % 5 == 0 || i % 3 == 0) { result += i; } } return result; } console.log(sumOfMultiples(1000)); console.log(sumOfMultiples(100000)); console.log(sumOfMultiples(10000000));