Trailing Zeroes of a Factorial and Binary Search

Revision en2, by vasugondaliya, 2020-02-01 04:22:07

Hey there, To find the number of trailing zeroes in a factorial, we need to find the power of twos and fives in the prime factorization of the factorial. Like in 5!, expansion of it is, 5!=5 x 4 x 3 x 2 x 1 = 2^3 x 3^1 x 5^1, and by finding minimum number out of the number of 2s and the number of 5s, which will always be number 5s as we will always have the extra number of 2s, we can find out the number of trailing 0s in factorial.

Now how to find the power of 5 or any prime number, we will follow the following procedure. Let's find the power of 5 in 200! 200! = 1x2x3x...x199x200 as we need to find the power of 5, we will neglect other terms and observe the numbers divisible by 5 200! = 5x10x15x...x195x200 x others taking out the powers of 5 from all the numbers, 200! = 5^(200/5) x (1x2x3x...x39x40) x others 200! = 5^(40) x (1x2x3x...x39x40) x others repeating the process in the inner bracket, 200! = 5^(40) x (5x10x15x...x35x40) x others 200! = 5^(40) x 5^(40/5) x (1x2x3x...x7x8) x others 200! = 5^(40) x 5^(8) x (5) x others The power of 5 in 200! = 40 + 8 + 1 = 49 In the same way we can find power of any prime number or any other number(with prime factorization and then following the process) using this method.

An application of it is in the problem: https://codeforces.me/contest/633/problem/B

In this question, we need to find the numbers whose factorial has the given number of zeroes 'm'. Easy and Dumb way to do this is by running a loop till we find the solution and as the value of m is small, we will even find the value in a reasonable time. But an optimized way is to perform binary search to the number of zeroes within the range.

The Lower limit of zeroes is 1 which is in 5!. The Upper limit is 100,000 which after a hit and trial way we find that to be in 400,005!. As the number of zeroes will increase on every fifth number, we will deal with the limit in that way too. The left limit of zero

Tags trailing zeroes, factorial, #binary search

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en5 English vasugondaliya 2020-02-01 15:11:14 444
en4 English vasugondaliya 2020-02-01 14:04:53 1545 (published)
en3 English vasugondaliya 2020-02-01 04:37:02 258
en2 English vasugondaliya 2020-02-01 04:22:07 1915
en1 English vasugondaliya 2020-01-31 18:32:43 107 Initial revision (saved to drafts)