How are the last non-zero digits of $(10^9)!$ computed?

668 Views Asked by At

Plugging in $(10^9)!$ in WolframAlpha gives a result of $...3160933638144$.I have an idea to how to calculate the last non-zero digit with modular arithmetics but how does WA compute the last 13 non-zero digits?

1

There are 1 best solutions below

0
On BEST ANSWER

I found the answer to this question after googling a bit. It is actually pretty simple.

when multiplying integers, any digit past the last 2 will not effect the last >2.

For instance, take 8!
8*7 = 56
56*6 = 336 = 36
36*5=180 = 80
80*4 = 320 = 20
20*3 = 60 60*2 = 120 = 20

Now we can use the same method for any number of last digits we want to find. The only thing we need to take care is to remove the zeroes.

I wrote this function in C++ that finds the last 12 non-zero digits of a factorial p. It works for p<1,000,000.

    long long temp=1;
    int i=1;
    long long factorial_digits(int p)
    {
    do
    {
    temp=temp*i;
    while(temp%10==0)
            temp=temp/10;
    temp=temp%1000000000000;
    i++;
    }

    while(i<=p);
        return temp;
    }