Leetcode_Factorial Trailing Zeroes (time-consuming problem)
If 0 is displayed, the multiples of 5 and 2 are displayed.
[N/k] indicates 1 ~ N can be divided by k, but the number that can be divided by 2 is redundant, so you only need to know the number that can be divided by 5. So how to calculate n! What is the number of all five in the prime factor? A simple method is to calculate floor (n/5 ). For example, 7! There is a 5, 10! There are two 5. In addition, there is one more thing to consider. There are more than five numbers, such as 25,125. For example, if we consider 28 !, We get an additional 5, and the total number of 0 is changed to 6. It is also easy to handle this problem. First, remove all single 5, then 25, remove the additional 5, and so on.
N! Number of suffixes 0 = n! Number of five in the prime factor
= Floor (n/5) + floor (n/25) + floor (n/125) + ....
Class Solution {/* So you only need to count the number of 5. So how to calculate n! What is the number of all five in the prime factor? A simple method is to calculate floor (n/5 ). For example, 7! There is a 5, 10! There are two 5. In addition, there is one more thing to consider. There are more than five numbers, such as 25,125. For example, if we consider 28 !, We get an additional 5, and the total number of 0 is changed to 6. It is also easy to handle this problem. First, remove all single 5, then 25, remove the additional 5, and so on. The formula for calculating the suffix 0 is as follows. N! Number of suffixes 0 = n! Number of five in the prime factor = floor (n/5) + floor (n/25) + floor (n/125) + .... */public: int trailingZeroes (int n) {int count = 0; int I = 5; while (I <= n) {count + = n/I; I * = 5;} return count ;}}; // Time Limit Exceeded. For example, enter 2147483647The other is:
class Solution {public: int trailingZeroes(int n) { int ret = 0; while(n) { ret += n/5; n /= 5; } return ret; }};//OKThe idea of another program is the same. One of them is that the data keeps increasing. when the data is large, it takes a long time. The other is that the data keeps decreasing, no similar issues have occurred.