Advertisement
imashutosh51

Factorial Trailing Zeroes

Oct 6th, 2022 (edited)
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. /*
  2. Logic:
  3. n!=1*2*3*4*5*6..*10*....15*....*20*...*25*....n
  4. Trailing zeros will be only generated by 2*5,no other factors exist for 10.
  5. so minimum of count of 2,count of 5 in factorial of n will be the answer.
  6. but there is one cache that,2 factors we can get after every alternate number
  7. eg 2,4,6,8,10 but 5 factor we get after every 5 numbers so obviously n! will
  8. have more no. of 2 in their factorial so just count the 5 in n!.
  9. after every 5 there will be one 5 do divide n by 5 but 25 have two 5 so
  10. divide n by 25 also because numbers which are divisible by 25 will give one five
  11. when divided by 5 and one five when divided by 25 and same goes on.
  12.  
  13. */
  14.  
  15. class Solution {
  16. public:
  17.     int trailingZeroes(int n) {
  18.         int ans=0;
  19.         int k=5;
  20.         while(k<=n){
  21.             ans+=(n/k);
  22.             k*=5;
  23.         }
  24.         return ans;
  25.     }
  26. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement