Factorial Trailing Zeroes -- leetcode

Source: Internet
Author: User

Factorial Trailing Zeroes -- leetcode

 

Given an integer n, return the number of trailing zeroes in n !.

Note: Your solution shocould be in logarithmic time complexity.

 

Basic Ideas:

Count n! The number of tails 0.

The ending number 0 is obtained by the product of 2, 5.

To count the number of 0, you need to count the number of 2, 5 factors. Because the number of 2 is more than 5, you only need to count the number of 5 factors.

For example, 5, 10, 15, 15, 20 n * 5, contains a 5.

25, 50, 75, n * 25, containing 2 5.

N * 125 contains 3 5.

...

Because the latter has an intersection with the former, the former has been counted. Therefore, you only need to add the latter one more time.

 

return n/5 + n/25 + n/125 + n/625 + n/3125+...;

 

Or write:

N/5 + (n/5)/5 + (n/5/5)/5 + (n/5/5/5)/5

 

 

class Solution {public:    int trailingZeroes(int n) {        int ans = 0;        int count = 0;        while (n) {            n /= 5;            ans += n;        }        return ans;    }};


 

return n/5 + n/25 + n/125 + n/625 + n/3125+...;

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.