leetcode--172 factorial Trailing Zeroes (n! How many 0 on the tail, the algorithm complexity is LG)

Source: Internet
Author: User

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

Note:your solution should is in logarithmic time complexity. (Your solution should be complex in logarithmic times.) )

Hide Tags:math


Title: given n, ask N! At the end of the number 0. Requires an algorithm complexity of LG

Problem Solving Ideas:

Idea One:

Think of the relatively simple, first practical for loop factorial operation, and then MOD10 to calculate the number of 0, but in the OJ check, timed out! , it is clear that the algorithm time complexity is not satisfied with the requirements of LG. Failed

The code is as follows:

public static int trailingZeroes1 (int n) {int sum=1;int count=0;for (int i = n; I >0; i--) {sum*=i;} while (sum!=0) {int remain=sum%10;if (remain==0) {count++;} else if (remain!=0) {break;} sum/=10;} return count;}

Idea II (recommended):

Only in the 2*5 time will appear 0, the whole 10 of the number can also be seen as the result of 2*5, so as long as there are more than 2 between N, how many 5 can be, it is not difficult to find that the number of 2 is greater than 5 of the number.


so you only need to record 5 of the number. However, it is important to note that a number like 25,125,625, divided by 5, is a multiple of 5, so you need to continue the loop processing.


(OJ Test succeeded)

The code is as follows:

public static int trailingzeroes (int n) {int result=0;while (n!=0) {result=result+n/5;n/=5;} return result;}

leetcode--172 factorial Trailing Zeroes (n! How many 0 on the tail, the algorithm complexity is LG)

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.