Search code examples
cfactorialtrailing

C program to find the trailing ZEROS at the end of a FACTORIAL of a given number


I have return the code to find a factorial and to display trailing zeros at the end of the factorial, but the output is wrong... could you please help me to find the mistake?

#include <stdio.h>

int main() {
    int m = 1, i, N, count = 0;

    scanf("%d", &N);

    for (i = 1; i <= N; i++) {
        m = m * i;
    }
    printf("%d", m);

    while (m > 0) {
        if ((m % 10) == 0) {
            count = count + 1;
            m = m / 10;
        }
        break;
    }
    printf("%d", count);

    return 0;
}

Solution

  • you have two problems

    • your collapse the two outputs so you see only one of them / you cannot see who is who, just add a separator between them
    • an else is missing when you count so you count to only up to 1 and the result is wrong from factorial 10

    So the minimal changes produce :

    int main()
    {
        int m=1,i,N,count=0;
    
        scanf("%d",&N);
    
        for(i=1;i<=N;i++)
        {
            m=m*i;
        }
        printf("%d\n",m); /* <<< added \n */
    
        while(m>0)
        {
          if((m%10)==0)
          {
            count=count+1;
            m=m/10;
          }
          else /* <<< added else */
            break;
        }
        printf("%d\n",count); /* <<< added \n */
    
        return 0;
    }
    

    after the changes :

    pi@raspberrypi:/tmp $ ./a.out
    5
    120
    1
    pi@raspberrypi:/tmp $ ./a.out
    10
    3628800
    2
    

    Of course that supposes first you are able to compute the factorial without overflow

    I also encourage you to check a value was read by scanf, checking it returns 1