Don't be intimidated by factorial

Source: Internet
Author: User

Problem description: given an integer N, the factorial n of n! How many zeros are there at the end? Example: n = 10, n! = 3628800, n! There are two zeros at the end

Analysis of the problem: Calculate the factorial of N and then check whether there are many zeros that are not practical. If n is slightly larger, it will take a lot of time. So let's analyze when we will add a zero, when there is a multiple of 2*5 or 10, the multiples of 10 can be decomposed into the N power of (2*5), obviously n! The number of 2 in the decomposed prime factor is much greater than 5, so you need to know n! You only need to know the number of five in the prime factor.

Simple code:

Optimization: Observe 50! The numbers, 5, 10, 15, 20, 25, 30, 35, 40, 45, and 50 in it, we can find that the multiples of each 5 contribute a 5, in addition, each 25 (5 square) and contribute another 5... So on, the Npower of 5 is in the power of 5, and the power of 5 is in the power of 2 .. The n-1 power of 5 contributes 5 each time, and the Npower of 5 contributes 5 again, so:

Code after optimization:

Expansion 1: n! Binary represents the position of the second digit 1

Problem Analysis: After 10 is multiplied by 10, there will be one more zero. Similarly, in binary, each multiplied by 2 will have one more zero, so you need to know the position of the second bit 1, only need to know n! The prime factor can be as many as 2.

Don't be intimidated by factorial

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: 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.