# My one-line solutions in 3 languages

• This question is pretty straightforward.

Because all trailing 0 is from factors 5 * 2.

But sometimes one number may have several 5 factors, for example, 25 have two 5 factors, 125 have three 5 factors. In the n! operation, factors 2 is always ample. So we just count how many 5 factors in all number from 1 to n.

One line code:

Java:

``````    return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
``````

C++:

``````    return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
``````

Python:

``    return 0 if n == 0 else n / 5 + self.trailingZeroes(n / 5)``

• yeah. but for the sake of completeness, i also calculated number of 2 factors by n/2 and check the minimum of n/2 and 5 factors. (which, probably should always be that of 5)

• I think it's not necessary. Because for every "5" there are at least two "2" factors to match it.
For example, we count from 5k+1 to 5(k+1), the [5k+1, 5k+2] has at least one "2", [5k+3, 5k+4] has at least one "2".

Even if there exist pow(5, k), there must have a number pow(4, k) less than it which can provide enough "2" factors.

• Your solution is so cool.

• why don't check less than 5? though no real different, but I still think it better.

• Your solution takes O(logn) time but it also has a logarithmic space complexity because it is not a tail recursion!

• Runtime O(k). No recursion. Here k is Log_5(n)
2 ms solution.

``````public class Solution {
public int trailingZeroes(int n) {
if(n<5) return 0;
int k=  (int) (Math.log(n) / Math.log(5));
int sum=0;
while(k>0)
{
sum+=n/Math.pow(5,k--);
}

return sum;
}
}``````

• my code below maybe more clean...it is no need to calculate k
`

``````  int ans=0;
while (n>=5) {
n/=5;
ans+=n;
}
return ans;
``````

• I guess both would give the same complexity.

• thank you very good solution
here is the iterative one line solution ...

``for(int res=0;;res+=(n/=5)) if(n==0) return res; ``

• So brilliant.

• Please explain how the complexity is logarithmic.

• Simplify this question to count the number of 5, brilliant!

• Brilliant, I also counted 2... That's redundant... Thx a lot

• why does count how many 5 factors in all number from 1 to n' mean `n / 5 + trailingZeroes(n / 5);`

• @wxl163530 see:

``5=1*5, 10=2*5, 15=3*5, 20=4*5, 25=5*5, 30=6*5 ... , 50=10*5=2*5*5, did you see that the numbers before each 5 in the multiplications: 1,2,3,4,5,6,...,10 has formed the (n/5) subproblem?``

• @guolei329 Got it, Thanks for sharing!

• I'm a beginner of python and I'm confused about the question that if n cannot be integer divided by 5, won't it return a decimal result? I thought your solution is smart but I just couldn't figure the question.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.