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;
           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


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:


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.


Thanks a lot rushi

1 Like

Thanks for the explaination bal_95

great explaination .

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