Skip to content
Advertisement

find sum of multiples 3 and 5, JS

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement