Java computes the number of n factorial end 0-leetcode 172 factorial Trailing Zeroes

Source: Internet
Author: User

Topic

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

Note:your solution should is in logarithmic time complexity.

Analysis

Note that the time complexity of the logarithm is solved, then it is impossible to roughly calculate the factorial of N and then look at the number of 0 at the end.

So careful analysis, N! = 1 * 2 * 3 * ... * N and the number of the end 0 is only related to the number of the multipliers in 5 and 2, because each occurrence of a pair of 5 and 2 will produce a 10 then N! There must be a 0 at the end. However, further analysis will find that 2 of the number of factors is definitely greater than the number of 5, so we just need to find n! The total number of factor 5 can be.

1. Given n then N/5 will get all the 5*1, 5*2, 5*3 ... the number of

2.N/25 will get the number of all 25*1, 25*2, 25*3 ....

3.N/125 will get all 125*1, 125*2, 125*3 .... Number of

........

There may be doubt that 25 of the two 5,125 in 3 5 will be less, but careful observation will find that in the 1th step has been the case of 25, the 2nd step is equivalent to the other 5 statistics in, and so on

Code
1      Public int trailingzeroes (int  n) {2         int rs = 0; 3          while (n! = 0) {4             rs + = (n/5); 5             n/= 5; 6         }7         return  rs; 8     }

And that's the result.

Java computes the number of n factorial end 0-leetcode 172 factorial Trailing Zeroes

Related Article

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.