Java [Leetcode 172]factorial Trailing Zeroes

Source: Internet
Author: User

Title Description:

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

Note:your solution should is in logarithmic time complexity.

Problem Solving Ideas:

For factorial, that is 1*2*3*...*n
[N/k] Represents the number of 1~n that can be divisible by k
Well, obviously,
[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 power must be greater than the power of 5

The code is as follows:

public class Solution {public    int trailingzeroes (int n) {    int res = 0;    while (n > 0) {    res + = N/5;    n/= 5;    }    return res;    }}

  

Java [Leetcode 172]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.