Online store~40 min2s · 256 MBtarget O(d × k × 10) time, O(k) spacenumber-theory · dp
You work on an online shop. Every product has a numeric code from 1 to 100,000,000,000,000, written in decimal without leading zeros. The marketing team likes a code when its digits add up to a multiple of k, and they avoid codes that contain one particular digit.
Your team lead asks: "How many codes between low and high are liked?" The range can hold 10^14 codes, so nobody can check them one by one.
Write count_codes(low, high, k, banned).
x with low ≤ x ≤ high that meet both rules.x add up to a multiple of k.x has no digit equal to banned. The decimal form has no leading zeros, so a leading zero is not a digit.Input: low = 1, high = 30, k = 3, banned = 7
Output: 9The codes up to 30 whose digit sum is a multiple of 3 are 3, 6, 9, 12, 15, 18, 21, 24, 27 and 30. Code 27 has the digit 7, so it is left out.
| Digits placed | Prefixes still equal to the limit | Prefixes already below it |
|---|---|---|
after 3 |
3 (sum 3, remainder 0) |
0 (not started), 1 (remainder 1), 2 (remainder 2) |
after 0 |
30 (remainder 0) |
00 (not started), 8 codes with remainder 0, 9 with remainder 1, 9 with remainder 2 |
The liked codes are the 8 codes below the limit with remainder 0, and 30, which gives 9.
Input: low = 7, high = 7, k = 7, banned = 3
Output: 1The only code is 7. Its digit sum is 7, which is a multiple of 7, and it has no digit 3.
Input: low = 100, high = 130, k = 5, banned = 0
Output: 4A code with a digit 0 is not allowed, so only 111 to 119 and 121 to 129 are left. Their digit sums are multiples of 5 for 113, 118, 122 and 127.
1 ≤ low ≤ high ≤ 100,000,000,000,0001 ≤ k ≤ 900 ≤ banned ≤ 9Even a fast program checks about 10^8 codes in a second, so 10^14 codes would take about 11 days. But a code has at most 15 digits. A method that places the digits one by one, and keeps only a small summary of the digits placed so far, needs about 15 × 90 × 10 steps.