Given an integer N , return the number of trailing zeroes in N !.
Title Description: Given an integer n, returns the number of suffix 0 in the number of n! (the factorial of N). Method One: First to obtain the factorial of N, and then calculate the number of the end 0, this method when n is relatively large, n! overflow class Solution {public:int trailingzeroes (int n) {if (n = = 0) return 0;int m = 0; int cnt = 0;int k = factorial (n), while (k) {m = k% 10;k = k/10;if (M = = 0) cnt++;elsebreak;} return CNT;} Computes the factorial int factorial (int n1) {if (N1 = = 0) of N to return 1;else{return n1*factorial (n1-1);}};
Method Two: Consider the prime factor of n!. The suffix 0 is always multiplied by the mass factor 2 and the mass Factor 5, and if we can count the number of 2 and 5, the problem is solved. Consider an example: n = 5 o'clock, 5! The mass factor (2 * 2 * 2 * 3 * 5) contains a 5 and three 2. Thus the number of suffix 0 is 1. n = 11 o'clock, 11! In the Mass factor ((2 ^ 8) * (3 ^ 4) * (5 ^ 2) * 7) contains two 5 and eight 2. So the number of suffix 0 is 2. It is easy to observe that the number of 2 in the mass factor is always greater than or equal to 5, so just count the number 5. So how do you calculate the number of all 5 of n! 's mass factor? An easy way is to calculate floor (N/5). For example, 7! There is a 5,10! of two 5. Besides, there is one more thing to consider. Numbers such as 25,125 have more than one 5. For example N=25, n!=25*24*23*...*15...*10...*5...*1= (5*5) *24*23*...* (5*3) * ... (5*2) * ... (5*1) *...*1, of which 25 can be regarded as 5*5, more than a 5, it should be added//handling the problem is also very simple, first for the n÷5, remove all the individual 5, then ÷25, remove the additional 5, and so on. The following is an inductive formula for calculating the suffix 0. Number of n! suffix 0 = 5 of n! quality factor = floor (N/5) + floor (N/25) + floor (n/125) + .... class Solution2{public:int trailingzeroes (int n) {int res = 0;while (n) {res = res + n/5;n = N/5;} return res;}};
Leetcode 172:factorial Trailing Zeroes