Chat app~15 min2s · 256 MBtarget O(q log n) time, O(q) spaceclassic twin: lc-172number-theory
You work on a chat app. A pack of n different stickers can be shown in n! different orders, where n! means 1 × 2 × 3 × ... × n. The settings screen prints that number in decimal, and the layout needs to know how many zeros it ends with.
Your team lead asks: "For each pack size, how many zeros end the number of orders?" Packs can have up to 1,000,000,000,000 stickers, and a request can hold 100,000 sizes.
Write trailing_zeros(sizes).
sizes[i] is the number of stickers in pack i. It can be 0, and 0! is 1.sizes[i]!. Trailing zeros are the zeros at the end of its decimal form.sizes[i]! has.Input: sizes = [5, 10, 25, 100]
Output: [1, 2, 6, 24]A trailing zero comes from a factor 10 = 2 × 5, and factors of 2 are never short. So count the factors of 5 in 1 × 2 × ... × n. For n = 25, the multiples of 5 are 5, 10, 15, 20 and 25, and 25 holds a second 5.
| n | n / 5 | n / 25 | n / 125 | Trailing zeros |
|---|---|---|---|---|
| 5 | 1 | 0 | 0 | 1 |
| 10 | 2 | 0 | 0 | 2 |
| 25 | 5 | 1 | 0 | 6 |
| 100 | 20 | 4 | 0 | 24 |
Each division is rounded down. For example, 25! is 15511210043330985984000000, which ends in 6 zeros.
Input: sizes = [0, 1, 4]
Output: [0, 0, 0]0!, 1! and 4! are 1, 1 and 24: no trailing zeros.
Input: sizes = [125]
Output: [31]125 gives 25 + 5 + 1 = 31 factors of 5.
1 ≤ len(sizes) ≤ 100,0000 ≤ sizes[i] ≤ 1,000,000,000,000You cannot build n!: the number 100,000! alone has 456,574 digits, and 1,000,000,000,000! has far more. Even counting the multiples of 5 one by one takes 200 billion steps for one size. The answer has to come from a formula that uses about 18 divisions for each size.