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'
}
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? 👇🤔
Top comments (2)
Maybe like this:
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
, where2 + 4 + 6 + 8
is the sum you're looking for.Good luck!
Great solution bro, I just tested it and it works 🔥