How many 0 are there at the end of the factorial of n?

Source: Internet
Author: User

In the joint iflab of the new question and answer on the book to see such a question, the effect is:

Give an integer n, ask N! How many 0 are at the end of (N's factorial)?

Because when n is very big, it is forced to calculate n! is impossible, so must find another way to solve the problem.

First of all, why would there be 0 at the end? Because 2*5 = 10,0 just came. So just ask out this n! How many of the 2 how many 5 times better, because 2 of the number of occurrences is certainly greater than 5, so only ask how many 5 to multiply the good.

Because the factorial of N is asked, and n! = 1*2*3*....*n

So: the number of N number that can be divisible by 5 = N/5

For example, n = 50, divisible by 5 has 5 10 15 20 25 30 35 40 45 50 total 10, i.e. 50/5=10

But don't forget 25 and 50, they can be split into 5*5 and 5*5*2, that is, the number that can be divisible by 5^2 will bring 2 0 (and so on 5 m-time will bring M 0 at the end).

So 50! At the end there is a 10+2=12 "0".

So the additional 5 of the number of M-order, we can from 5 to 5*5 to 5*5*5 ... Slowly looking for the big.

So the specific code is as follows (using the Web, 2L answer)

1 intTotalzero (intN)2 {3     intTotal =0;4      while(N >5)5     {6n = (n-(N)5)) /5;7Total + =N;8     }9     returnTotal ;Ten}

The nth cycle here is equivalent to the number of 5^n divisible by the sum, and the result is added.

The effect of the code is equivalent

First: number that can be divisible by 5 = N/5

Second time: number divisible by 25 = N/5/5

The third time .....

The fourth time ....

Although the number of n is changed after each cycle, the overall effect is equivalent to the number of 5^n divisible by the sum.

How many 0 are there at the end of the factorial of n?

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.