Given an integer n, and return the number of trailing zeroes in n!.
Note:your solution should is in logarithmic time complexity. (Your solution should be complex in logarithmic times.) )
Hide Tags:math
Title: given n, ask N! At the end of the number 0. Requires an algorithm complexity of LG
Problem Solving Ideas:
Idea One:
Think of the relatively simple, first practical for loop factorial operation, and then MOD10 to calculate the number of 0, but in the OJ check, timed out! , it is clear that the algorithm time complexity is not satisfied with the requirements of LG. Failed
The code is as follows:
public static int trailingZeroes1 (int n) {int sum=1;int count=0;for (int i = n; I >0; i--) {sum*=i;} while (sum!=0) {int remain=sum%10;if (remain==0) {count++;} else if (remain!=0) {break;} sum/=10;} return count;}
Idea II (recommended):
Only in the 2*5 time will appear 0, the whole 10 of the number can also be seen as the result of 2*5, so as long as there are more than 2 between N, how many 5 can be, it is not difficult to find that the number of 2 is greater than 5 of the number.
so you only need to record 5 of the number. However, it is important to note that a number like 25,125,625, divided by 5, is a multiple of 5, so you need to continue the loop processing.
(OJ Test succeeded)
The code is as follows:
public static int trailingzeroes (int n) {int result=0;while (n!=0) {result=result+n/5;n/=5;} return result;}
leetcode--172 factorial Trailing Zeroes (n! How many 0 on the tail, the algorithm complexity is LG)