I was practicing in CodeWars with katas that I have already solved before. Here is the problem:
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 the number is a multiple of both 3 and 5, only count it once.
It’s a very simple kata, but when I tried to solve it my solution didn’t work. I checked my previous solution and I notice that is almost identical to my current one. However, the first code return the correct output and the second doesn’t.
First solution (it works)
function solution(number){
let sum = 0;
if (number < 0) {
return 0;
}
for (i = 1; i < number; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
}
return sum;
}
Second solution (doesn’t work)
function solution(number){
let count = 0;
if (number < 0) {
return 0;
}
for (i = 1; i < number; i++) {
if (i % 3 === 0 || i % 5 === 0) {
count += 1;
}
}
return count;
}
What am I missing?
The test is with number 10. It should return 23, but in the second code it returns 4. I tried both codes in the console.
Raúl Galicia is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.