Hey everyone,
When I was following the JavaScript exercise 8 about sum of multiples of 3 and 5 I think I found a bud in the code Mosh showed in the video. I don’t know if this is not checked by him by mistake or if it was intentionally.
The exercise is to create a function that adds the multiples of 3 and 5 under a limit number:
For example
If the limit number is 10, the multiples of 3 and 5 are: 3, 6, 9 and 5, 10.
Then he would add those and the result is 33.
But if the limit number is 15, the multiples are: 3, 6, 9, 12, 15 and 5, 10, 15.
In this case 15 is double in the sequence and I realised in this code the result was 60 instead of 75 because he didn’t add the doubled 15.
The code he used:
console.log(sum(15));
function sum(limit) {
let sum = 0;
for (let i = 0; i <= limit; i++) if (i % 3 === 0 || i % 5 === 0) sum += i;
return sum;
}
I did try to code a function that would add numbers if they occur in both the multiples of 3 and 5 but its very long and since I’m really new to coding its probably not efficient, but it does work
I was hoping if someone that knows more could also try to code this problem so I could see how you would solve this problem on a higher level than me XD
btw this is what I came up with:
sum(15);
function sum(limit) {
i = 0;
let sumMultipliedByThree = 0;
let sumOfThree = 0;
while (sumMultipliedByThree <= limit) {
i++;
sumOfThree += sumMultipliedByThree;
sumMultipliedByThree = 3 * i;
}
i = 0;
let sumMultipliedByFive = 0;
let sumOfFive = 0;
while (sumMultipliedByFive <= limit) {
i++;
sumOfFive += sumMultipliedByFive;
sumMultipliedByFive = 5 * i;
}
console.log(sumOfThree + sumOfFive);
}
Thanks for the help in advance, this is really just a curiosity question for people who like to answer