DEV Community

Cesar Del rio
Cesar Del rio

Posted on

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

Instructions

Your Job
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'
}
Enter fullscreen mode Exit fullscreen mode

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'


What do you think about this solution? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (2)

Collapse
 
snigo profile image
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;
}
Enter fullscreen mode Exit fullscreen mode

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!

Collapse
 
cesar__dlr profile image
Cesar Del rio

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