Solution for Multiples of 3 and 5

Alternative solution for Multiples of 3 and 5, guide

Below solution, credit to JeremyLT's suggestion below & wiki article 1 + 2 + 3 + 4 + ⋯

Solution 1, complexity O(1)
function multiplesOf3and5(number) {
  // multiples of 3
  const higherVal3 = parseInt((number - 1) / 3, 10);
  const sum3 = (higherVal3 * (higherVal3 + 1) / 2) * 3;

  // multiples of 5
  const higherVal5 = parseInt((number - 1) / 5, 10);
  const sum5 = (higherVal5 * (higherVal5 + 1) / 2) * 5;

  // common multiples of 3 & 5, we need to subtract these as they are added twice
  const higherVal15 = parseInt((number - 1) / 15, 10);
  const sum15 = (higherVal15 * (higherVal15 + 1) / 2) * 15;

  return sum3 + sum5 - sum15;
}

Existing solution and the below one, both have O(n) complexity, but the absolute number of loops are less in the solution proposed below

Solution 2, complexity O(n)
function multiplesOf3and5(num) {
  // max number we need to loop to
  const loopTo = parseInt(num / 3, 10);
  let sum = 0;
  for (let i = 1; i <= loopTo; i++) {
    const multiple5 = 5 * i;
    const multiple3 = 3 * i;
    // a fail-safe check, should always be true
    if (multiple3 < num) {
      sum = sum + multiple3;
    }
    // if it is divisible by 3, don't add, above condition will take care
    if (multiple5 < num && multiple5 % 3 !== 0) {
      sum = sum + multiple5;
    }
  }
  return sum;
}

The pushing into the multiples array is unnecessary, and it will greatly slow down your code.

Really, I think we should add the O(1) solution instead of another O(n).


If you aren’t familiar with the O(1) solution

Hints
  • 3+6+9+… = (1+2+3+…)*3

  • multiples of both 3 and 5 are divisible evenly by 15

That’s interesting, I didn’t think of that. Thanks for sharing!!

1 Like

I’m off to bed, but if you’re interested in trying to impl the O(1), I can look at it in the morning for inclusion.

Thanks to your suggestion and wiki article I was able to figure it out.

1 Like

Thank you for your guide post contribution. I have taken your suggestions and included them in the guide post.

We look forward to your further contribution.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.