Number of zeros in a factorial number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lauramaria
    New Member
    • Aug 2012
    • 4

    Number of zeros in a factorial number

    It is given an integer "p". I have to find a number "n" for which "n factorial" has "p" numbers of zero at the end. Here is the solution i thought, but i am not sure if it is a solution for this problem. Do i have to make a function to calculate the factorial and another function to get the zeros?


    Code:
    int p;
    int count5=0;
    int i;
    int copy_i;
    
    printf("Enter p: ");
    scanf("%d",&p);
    
    for(i=1; ;i++)
    {
        copy_i=i;
    
        while(copy_i/5)
        {
            if(copy_i%5==0)
            {
                count5++;
                copy_i=copy_i/5;
            }
            else
            {
                break;
            }
        }
    
        if(count5==p)
        {
            printf("The minimum number n is: %d.",i);
            break;
        }
        else if(count5>p) 
        {
            printf("No match for n! with %d zero.",p);
            break;
        }
    
    }
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Factorials get very big very fast. n! becomes too big to be represented in a C variable for depressingly small values of n. Besides that, a program to compute factorials can run disappointingly slow as n increases. Thus, I suggest you look for some alternative to the brute force algorithm suggested in your original post.

    If a number ends in p zeroes, then it must be true that the number is divisible by 10^p. Find a list of distinct factors of 10^p and the largest value in that list will be the value n that you are looking for. Spend a lot of pencil-and-paper time to make sure your algorithm is correct before you write any code.

    Comment

    Working...