Factorial Trailing Zeroes--leetcode

Source: Internet
Author: User

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

Note: Your solution should is in logarithmic time complexity.


Train of thought: for a number of factorial after how many 0, a number n factorial end of how many 0 depends on the number of factors from 1 to n the number of 2 and 5, and the number of 2 is far more than the number of 5, so to find out the number of 5. The solution to the number of factors given in the 5 method is to use N is divided by 5, until the result is 0, and then the intermediate results accumulated. For example, 100/5 = 20, 20/5 = 4, 4/5 = 0, the number of factor 1 in 100 to 5 is (20 + 4 + 0) = 24, which is 100 24 at the end of factorial. In fact, divided by 5, because each interval of 5 number has a number can be divisible by 5, and then in these can be divisible by 5 of the number, each interval 5 number and one can be divided by 25, it is necessary to divide again, ... Until the result is 0, it means that no number can continue to be divisible by 5.

#include <iostream> #include <vector> #include <string>using namespace std;int trailingzeroes (int n) {   int count=0;   int num =n,i;   while (num)   {      count + = NUM/5;      num = NUM/5;   }   return count;      } int main () {    cout<<trailingzeroes (<<endl;    ) System ("pause");    return 0;    }


Factorial Trailing Zeroes--leetcode

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.