Search code examples
c++mathfactorial

Why is my code for finding number of trailing zeros in a factorial returning garbage value


I want to find the number of trailing zeros in a factorial, but my code is returning garbage values.

#include<iostream>
using namespace std;

int main()
{   
   long int n;
   cin>>n;
   int z=0;
   while(n>0)
   {
      n=n/5;
      n=z+n;
      z=n;
   }
   return z;
}

Solution

  • I understand your code as follows: Your input is n and you want to calculate how many trailing zeros n! has. In this case your while loop has to look the following way:

    while(n > 0)
    {
        n = n / 5;
        z = z + n;
    }
    
    // After running the loop, directly output the result.
    cout << "z: " << z;
    

    This gives me 249 trailing zeroes in the expansion of 1000! And 1151 trailing zeroes for 4617!

    According to this page that should be correct.