Leetcode172:factorial Trailing Zeroes

Source: Internet
Author: User

anintegerreturnthenumberofinintime complexity.

This problem requires solving the number of end 0 in the factorial in logarithmic time.

The number of factorial in 0 is determined by the number of factors 2 and 5, and because factorial is the number of consecutive n, so the number of 2 is more than the number of 5, so the number of 0 is equal to the number of 5 of each factor.

Take 10! For example Analysis:
10! =10*9*8*7*6*5*4*3*2*1
There are 5 of the factors that contain factor 2, 10=2*5,8=2*4,6=2*3,4=2*2,2=2*1
The remaining 5 numbers, divided by 2, are 5,4,3,2,1, which still contain 2 of 4, 2,
After dividing by 2, there is still a number with 2 2
So 10! Contains 2 of the number is "10/2" + "10/2^2" + "10/2^3" =5+2+1
Note: "Num" represents the largest integer that is not greater than num
You can also use the same method to find the number of factor 5, and this problem is to find the number of 5 factors.

Runtime:3ms

class Solution {public:    inttrailingZeroes(int n) {        int result=0;        while(n>=5)        {            result+=n/5;            n/=5;        }        return result;    }};

Leetcode172:factorial Trailing Zeroes

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.