Counting Zeros at the end of Factorial

Problem code : FCTRL
int main() {
int t = 0 ;
cin >> t ;

    for(int i = 0 ; i<t;i++){
        int N ;
        cin >> N;
            int ans = 0;
            int val = 5;
           while(val <= N){
               ans+= N/val;
               val*=5;
           }     
           cout << ans << endl;
  }

Cna anyone explain the concept behind this approach

for Finding zeros in Factorial
There is standard formula
Your code is also implemented using the same
For logic you more often have to google it as many people know the formula and unaware about logic behind it .

1 Like

10=2*5

You will get multiples of 2, but it is because of the multiples of 5 that you get multiples of 10s or zeroes at the end.

Let’s take 12! as an example.

12! = 1x2x3x4x5x6x7x8x9x10x11x12

Break them into elemental integers:

1x2x3x2x2x5x2x3x7x2x2x2x2x3x3x2x5x11x2x2x3

As you can see, you can make two (2,5) pairs which make 10. Other than them, you can’t get 10. So, the answer will be 2.

So, the answer will be the number of 5s in the elemental multiplication for n!.

The above code counts those number of 5s.

3 Likes

Thanks a lot rushi

1 Like

Thanks for the explaination bal_95

great explaination .
@bal_95

Today I also got to know about logic .
Thanks from my side also .
@jayant12_28