DEV Community

Discussion on: Sum of 3 or 5 Multiples - Problem => Solution

Collapse
 
gnsp profile image
Ganesh Prasad

This can be solved way more efficiently without using arrays or loops, if we approach it mathematically.

Let's assume:

  • sum of multiples of 3 or 5 below 1000 is a
  • sum of multiples of 3 below 1000 is b
  • sum of multiples of 5 below 1000 is c
  • sum of multiples of 3 and 5 (that is, multiples of 15) below 1000 is d

then, clearly, a = b + c - d
To find, a, we can start with finding the values of b, c and d.

To solve this, let's write find an algorithm to find the multiples of x below y.

  • The number of multiples of x (strictly) below y is n = Math.floor((y-1) / x)
  • The smallest multiple of x is always x.
  • The multiples of x below y form an Arithmetic Progression (AP), x, 2x, 3x ... nx
  • Sum of the AP is s = x + 2x + 3x + ... + nx
  • => s = x * (1 + 2 + 3 + ... + n )
  • => s = x * n * (n + 1) / 2

Let's write a function for that,

function sumOfMultiplesBelow (x, y) {
    const n = Math.floor((y-1) / x);
    return x * n * (n + 1) / 2;
}

const b = sumOfMultiplesBelow(3, 1000);
const c = sumOfMultiplesBelow(5, 1000);
const d = sumOfMultiplesBelow(15, 1000);

const a = b + c - d;
console.log(a);

This way, we solve the problem in O(1) time and space complexity.