I'm currently training on codewars, and today was multiples of 3 and 5. I tried with a casual solution using reduce ternary, and it worked.
I then tried to solve it with recusrive function. Instructions are as follow :
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 (for languages that do have them).
Link is here
const input = 10
function sum35(num){
num = num - 1
const lastThree = num - num%3
const threeQuantity = lastThree/3
const lastFive = num - num%5
const fiveQuantity = lastFive/5
return getSum(threeQuantity,3,lastThree) getSum(fiveQuantity, 5, lastFive)
function getSum(n, first, last) {
return (n/2)*(first last)
}
}
console.log(sum35(10))
CodePudding user response:
Defining res
as a global is very likely the problem: its value will be reused for subsequent calls of the function.
Change your function to take res
as a parameter. If the signature must define only a single parameter, using an inner function would be an idea.
Here's a solution using a nested function, simplifying some of the unnecessary complications and duplications:
function solution(n) {
let res = 0;
function _solution(n) {
if(n <= 0) {
return 0;
}
if(n % 3 != 0 && n % 5 != 0) {
return _solution(n - 1);
}
res = n;
_solution(n - 1);
return res;
}
return _solution(n - 1);
}
But note that this is not a "clean" recursive approach, because the function is actually a closure and has a side-effect: modifying the value of the outside variable res
. For a proper recursive implementation, see yanai edri's answer.