Factorial Trailing Zeroes

题目
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.

答案

note: every trailing 0 is made possible by a prime factor 2 and 5
In n!, you will always get more 2s than 5s.
So we will focus on counting how many prime factor 5s there are in n!

Example, when n = 25
we know the prime factors of n! = 25 come from 5, 10, 15, 20, 25
there are a total of 5 such prime factors(calculated by 25/5 = 5)

but note that 25 = 5*5, that tells us that some numbers have more than one 5 as its prime factor. This should be taken care of!

class Solution {
    public int trailingZeroes(int n) {
        if(n == 0) return 0;
        else return n / 5 + trailingZeroes(n/5);
    }
}

你可能感兴趣的:(Factorial Trailing Zeroes)