Use PowerMod and ModularInverse to find the first non-zero digit for 10000! (factorial for 10,000) from right. Inspired by a recent Michael Penn's YouTube video from Mathematics Magazine problem 1975. Chinese remainder theorem used with entry-level p-adic analysis in generalized version of this problem.

Cheat with One liner

In[]:=
IntegerDigits[10000!][[-Total[IntegerExponent[#,5]&/@Range[10000]]-1]]
Out[]=
8

Analysis

Usually for factorial trailing zero problem, we only need to consider the exponent of 5 or the 5-adic property:
In[]:=
fiveAdic=IntegerExponent[#,5]&/@Range[10000];
In[]:=
twoAdic=IntegerExponent[#,2]&/@Range[10000];
Because there are always more two’s than five’s in the final product:
In[]:=
Total[twoAdic]>Total[fiveAdic]
Out[]=
True
So there are exactly 2499 trailing zeros
In[]:=
Total[fiveAdic]
Out[]=
2499
The first non-zero digit is at the 2500th position from right.
Find the equivalence of
-2499
2
in the
mod(5)
world using efficient PowerMod function:
In[]:=
inv=ModularInverse[PowerMod[2,Total[fiveAdic],5],5]
Out[]=
2
The whole factorial,
10000!
, with all 2499 number of 5’s removed and then take modulo 5 again:
In[]:=
Mod[inv*Fold[Mod[(#1*#2/5^IntegerExponent[#2,5]),5]&,1,Range[2,10000]],5]
Out[]=
3
Then the only options for the 2500th digit is 8:
In[]:=
Cases[Range[0,9],_?(EvenQ[#]&&Mod[#,5]==3&)]
Out[]=
{8}

Extend to last six digits

Almost identical code but with careful choice of exponents by theory of p-adic analysis:
In[]:=
inv=ModularInverse[PowerMod[2,Total[fiveAdic],5^6],5^6]
Out[]=
12502
Must use the exponent of 5 in division for all numbers in the factorial:
In[]:=
Mod[inv*Fold[Mod[(#1*#2/5^IntegerExponent[#2,5]),5^6]&,1,Range[2,10000]],5^6]
Out[]=
883
The last six digits is found using Chinese remainder theorem:
In[]:=
ChineseRemainder[{0,883},{2^6,5^6}]
Out[]=
579008
Check with one liner:
In[]:=
IntegerDigits[10000!][[-2505;;-2500]]
Out[]=
{5,7,9,0,0,8}

CITE THIS NOTEBOOK

Find the 2500th digit in 10000! (Number theory warmup for 2025)​
by Shenghui Yang​
Wolfram Community, STAFF PICKS, January 6, 2025
​https://community.wolfram.com/groups/-/m/t/3351570