6 kyu · algorithms

Multiples of 3 or 5

MathematicsAlgorithms

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.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.

Additionally, if the number is negative, return 0.

Note: If a number is a multiple of both 3 and 5, only count it once.

Courtesy of projecteuler.net (Problem 1)

Solutions

01-solution.jsView on GitHub ↗
function solution(n) {
  if (n < 0) return 0;
  let s = 0;
  for (let i = 0; i < n; i++) {
    if (i % 5 === 0 && i % 3 === 0) {
      s += i;
    } else if (i % 5 === 0) {
      s += i;
    } else if (i % 3 === 0) {
      s += i;
    }
  }
  return s;
}

function solution(n) {
  if (n < 0) return 0;
  return Array.from({ length: n }).reduce((s, _, i) => {
    if (i % 5 === 0 && i % 3 === 0) {
      s += i;
    } else if (i % 5 === 0) {
      s += i;
    } else if (i % 3 === 0) {
      s += i;
    }
    return s;
  }, 0);
}

function solution(n) {
  if (n < 0) return 0;
  return Array.from({ length: n }).reduce((s, _, i) => {
    if (i % 5 === 0 || i % 3 === 0) {
      s += i;
    }
    return s;
  }, 0);
}

function solution(n) {
  if (n < 0) return 0;
  return Array.from({ length: n }).reduce(
    (s, _, i) => (i % 5 === 0 || i % 3 === 0 ? (s += i) : s),
    0
  );
}