forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactorial_trailing_zeroes.py
More file actions
42 lines (32 loc) · 911 Bytes
/
factorial_trailing_zeroes.py
File metadata and controls
42 lines (32 loc) · 911 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
'''
Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Input: 3
Output: 0
Output explanation: 3! = 6, no trailing zero.
Input: 5
Output: 1
Output explanation: 5! = 120, one trailing zero.
=========================================
Find how many 5s are in range 0-N (more explanation in the solution).
Time Complexity: O(logN)
Space Complexity: O(1)
'''
############
# Solution #
############
def trailing_zeroes(n):
# 0s are produced when 2 and 5 are multiplied
# because 2 * 5 = 10
# so you'll need to count how many 2s and 5s are there
# 2s are always more than 5s
# so count just how many 5s are in that range
res = 0
k = 5
# find all powers of 5
# 25 has 2 5s, 125 has 3 5s, etc
while k <= n:
res += n // k
k *= 5
return res