Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Count trailing zeros of n! (number of factors 5).
Problem: Count trailing zeros of n! (number of factors 5).
def tz(n):
c = 0
while n:
n //= 5; c += n
return c
print(tz(25), tz(100), tz(1000))What is printed?- A. 5 20 200
- B. 6 24 248
- C. 5 24 249
- D. 6 24 249
Correct answer: D. 6 24 249
Each trailing zero needs a factor 10 = 2 × 5, and 2s are plentiful, so count 5s: ⌊n/5⌋ + ⌊n/25⌋ + ⌊n/125⌋ + … 25 → 5 + 1 = 6; 100 → 20 + 4 = 24; 1000 → 200 + 40 + 8 + 1 = 249. Counting only ⌊n/5⌋ misses the extra 5s in 25, 125, … O(log n).
More Coding Interview Problems questions
- Problem: Reverse the digits of a 32-bit signed integer, returning 0 if the result overflows. python def rev(x): s = -1 if x < 0 else 1 r =…
- Problem: Find the integer x (0 ≤ x < m) such that 3x ≡ 1 (mod 11) using the extended Euclidean algorithm. python def ext(a, b): if b == 0…
- Problem: Return the excel-style column title for a column number (1 → A, 26 → Z, 27 → AA). python def title(n): s = '' while n: n -= 1 s =…
- Problem: Return the number formed by the most significant digit of the sum of digits repeatedly added until one digit remains (digital…
- Problem: Count pairs (i < j) with a[i] > a[j] (inversions) in an array of n = 2 × 10⁵ values. Which approach runs within a 1-second limit?
- Problem: Answer q = 10⁵ queries 'sum of a[l..r]' on a static array of n = 10⁵ values. Which approach is best?