Skip to content

Instantly share code, notes, and snippets.

@izanbf1803
Created January 5, 2019 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izanbf1803/72b89bffff9d490c2976ba11b65b1b6d to your computer and use it in GitHub Desktop.
Save izanbf1803/72b89bffff9d490c2976ba11b65b1b6d to your computer and use it in GitHub Desktop.
Find last m non-zero digits of n!
# Find last m non-zero digits of n!
n, m = map(int, input().split())
cnt = 0
power = 5
while n // power > 0:
cnt += n // power
power *= 5
print(f"{n}! has {cnt} zeros.")
mod = 10**m
factorial = 1
for i in range(2, n+1):
k = i
while k % 5 == 0:
k //= 5
while k % 2 == 0 and cnt > 0:
k //= 2
cnt -= 1
factorial = factorial * k % mod
s = str(factorial)
fill_zeros = "0"*(m-len(s))
print(f"Last {m} non-zero digits of {n}! = {fill_zeros}{s}")
@izanbf1803
Copy link
Author

You need to give a line input like "2019 3".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment