# how to find the last non-zero digit of $n$

I want to know how to find the last non-zero digit of $n$.

For example $n = 100!$

my try:

First i have to know how much Zeros $100!$ has so i did this:

$$E_{5}100 = \sum _{1\leq k <n} \Bigg[\frac{100}{5^{k}}\Bigg] =\Bigg[\frac{100}{5}\Bigg] + \Bigg[\frac{100}{25}\Bigg] = 24$$

So $100!$ has $24$ zeros which means that the last digit of $\quad\frac{100!}{10^{24}}\quad$ is the number that i´m looking for.

so if $x = \frac{100!}{10^{24}}$ i need to find $x (mod 10)$ to get it but here is where i got stuck...

• First multiply digits 1 to 9 and note the last non zero number this might be your answer which will be 4. This is how you will get the last number. – Jasser Sep 22 '14 at 7:50
• @user291957 actually, $9! = 362880$, whose last non-zero number is 8. – symmetricuser Sep 22 '14 at 8:42
• Yes yes it's 8 @user125084 . Apologies. – Jasser Sep 22 '14 at 8:45

    int digit=1;
int tmp;
int cnt_2=0;
for(i=1;i<=n;i++){
tmp =i;
while(tmp%2==0){
cnt_2++;
tmp = (tmp>>1);
}
while(tmp%5==0){
cnt_2--;
tmp = tmp/5;
}
digit = (digit*tmp)%10;
}
if(cnt_2>=0){
for(i=1;i<=cnt_2;i++){
digit = ((digit<<1)%10);
}
}
if(cnt_2<0){
digit=5;
}


This is the code in C which I wrote to find the last nonzero digit of n!

• Can you provide formal mathematical description of your algorithm in addition to the programming implementation? – Vlad Aug 20 '15 at 17:14
• sorry ! I am not so good at mathematics. But I can try to explain what I did here. – nhimran Aug 22 '15 at 4:57