Factorial Trailing Zeroes
LeetCode 172 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Σ n // 5^i.
ನಾನು Factorial Trailing Zeroes (LeetCode 172) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Other ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Each trailing zero comes from a factor 10 = 2 × 5, and factors of 2 are plentiful, so count factors of 5 in n!: multiples of 5 give one, multiples of 25 another, and so on.
Approach
- 1
count = 0.
- 2
Repeatedly n //= 5 and add n to the count.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Count factors of 5PythonO(log n) time
class Solution:
# def getZeroes(self,n:int) ->int:
# count=0
# while n%10==0:
# count+=1
# n=n/10
# return count
# def trailingZeroes(self, n: int) -> int:
# ans =1
# for i in range(2,n+1):
# ans=ans*i
# return self.getZeroes(ans)
#def trailingZeroes(self, n: int) -> int:
#how many steps we can have 5,10,20,30
#5! - 120 - 1*2*3*4*5 - 1 step with a distance of 5
#6!-720
#10! - 3628800 - 1*2*3*4*5*6*7*8*9*10 - 2 step with a ditance of 5
def trailingZeroes(self, n: int) -> int:
#how many multiples of 5 contribute to the trailing
# 5 25 125
count=0
while n>0:
n=n//5
count+=n
return count
"""
10>0
10/5 =2
count+=2
"""Factorial Trailing Zeroes — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Factorial Trailing Zeroes ಹಿಂದಿನ intuition ಏನು?
Each trailing zero comes from a factor 10 = 2 × 5, and factors of 2 are plentiful, so count factors of 5 in n!: multiples of 5 give one, multiples of 25 another, and so on.
Factorial Trailing Zeroes (LeetCode 172) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. count = 0. 2. Repeatedly n //= 5 and add n to the count.
Factorial Trailing Zeroes ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(log₅ n). Space: O(1). (Accepted approach: Count factors of 5.)
Factorial Trailing Zeroes ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Computing n! directly overflows (and is slow) quickly.