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;
}