# Help with CodeWars Kata: Number of trailing zeros of N!

i’m working on this kata: https://www.codewars.com/kata/number-of-trailing-zeros-of-n/train/javascript

i’m not sure why my algorithm isn’t working:

``````function zeros (n) {
let divider = 1
let sum = 0

const dividerIncrementor = () => divider = divider * 5

while (dividerIncrementor() <= n){
sum = sum + n/dividerIncrementor()
}
return Math.floor(sum)
}
``````

when I console.log(sum = sum + n/dividerIncrementor()) manually up until the point where dividerIncrementor() <= n I get the right outputs but when I run zeros(n) it only gives me the last iteration of sum + n/dividerIncrementor() instead of adding up all the previous sums. What gives?

for instance:
when n = 30
the correct output should be 7 but instead I’m getting 1 (the sum of the 2nd iteration of sum = sum + n/dividerIncrementor()). It’s not adding the 1st iteration of sum which is 6. It seems like the while loop is resetting the value of sum each time it loops but that shouldn’t be the case?

I believe you are having issues because your dividerIncrementor function is mutating the divider variable every time it is invoked, including when it is being checked inside the conditional for the while loop. So it is incrementing divider two times for every one time the block of code in the while loop runs.

Check out the logs for it here to see what I mean:

``````function zeros(n) {
let divider = 1;
let sum = 0;

const dividerIncrementor = () => {
divider = divider * 5;
console.log('dividerIncrementor invoked, divider = ' + divider);
return divider;
};

while (dividerIncrementor() <= n) {
sum = sum + n / dividerIncrementor();
console.log('while loop block executed, sum = '+ sum);
}
return Math.floor(sum);
}
``````

Instead of having a separate `dividerIncrement` function, you could try just incrementing `divider` inside the while loop, and checking the value of divider in the conditional.

1 Like

doh! should’ve known that! Thanks for the help!

here’s my final solution (the correct solution):

``````function zeros (n) {
let divider = 1
let sum = 0

while (divider <= n){
sum = Math.floor(sum + n/(divider *= 5))
}
return sum
}
``````
1 Like