172. Factorial Trailing Zeroes

Source: Internet
Author: User

problem Source: https://leetcode.com/problems/factorial-trailing-zeroes/

Problem Description: Given an integer N , return the number of trailing zeroes in N !.  Note: Your solution should is in logarithmic time complexity. (requires a trailing 0 number to return the value n! note the complexity)

My Code (3MS):

1) First simplify the problem (avoid factorial): n! decomposition =2x * 3y * 5z * ...; Obviously we ask for Min (x,z) and Min (x,z) ==z;

2) Next how to represent the number of 1~n that can be divisible by k: [n/k]

3) Proof: for factorial, which is 1*2*3*...*n, it is clear that:
[N/2] > [N/5] (on the left is 2 increase 1, the right is 5 increase 1)
[N/2^2] > [n/5^2] (on the left is 4 increase 1, the right is 25 increase 1)
[N/2^p] > [N/5^p] (on the left is the 2^p increase 1, on the right is every 5^p 1)
With the rise of power p, the probability of appearing 2^p is much greater than the probability of 5^p. So the left side of the addition and must be greater than the right side of the sums, that is, n! quality factor decomposition, 2 of the power must be greater than 5 recurses; so the right and the answer.

int trailingzeroes (int n) {
	int count = 0;
	while (n) {
		count + = N/5;
		n = n/5;
	}
	return count;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.