## DEV Community is a community of 871,998 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Cesar Del rio

Posted on

# #36 - Sum of Multiples CodeWars Kata (8 kyu)

## Instructions

Find the sum of all multiples of n below m

Keep in Mind
n and m are natural numbers (positive integers)
m is excluded from the multiples

Examples

sumMul(2, 9) ==> 2 + 4 + 6 + 8 = 20
sumMul(3, 13) ==> 3 + 6 + 9 + 12 = 30
sumMul(4, 123) ==> 4 + 8 + 12 + ... = 1860
sumMul(4, -7) ==> "INVALID"

## My solution:

``````function sumMul(n,m){
let r = 0;
for(let i = 1; i*n<m; i++){
r+=i*n
}
return r > 0 ? r : 'INVALID'
}
``````

## Explanation

I made an r variable, in which I'll store the sum result.

let r = 0;

Then I used a for loop that will iterate until the result of i*n is smaller than "m".
Inside of this loop I'll change the value of "r" to the sum of "r" plus i*n

for(let i = 1; i*n<m; i++){
r+=i*n
}

At the end if "r" is more than 0, I'll return r, else I'll return 'INVALID'

return r > 0 ? r : 'INVALID'

## Discussion (2)

Igor Snitkin

Maybe like this:

``````function sumMul(n, m) {
if (m <= n) return "INVALID";
const l = m - (m % n || n);
return (n + l) / 2 * l / n;
}
``````

This is based on the fact that the average of `[2, 8]` is the same as the average of `[2, 4, 6, 8]`, which means that `(2 + 8) / 2 === (2 + 4 + 6 + 8) / 4`, where `2 + 4 + 6 + 8` is the sum you're looking for.

Good luck!

Cesar Del rio

Great solution bro, I just tested it and it works 🔥