Monitoring~25 min2s · 256 MBtarget O(top + n) time, O(top) spacenumber-theory
You work on a monitoring system. To keep its numbers small, it stores every sum modulo a prime p. A dashboard needs the mean of each series: its sum divided by the number of samples.
In arithmetic modulo p, the mean of a series is one number m from 0 to p - 1. It is the m for which count × m leaves the same remainder as total. Your team lead asks: "Give me that mean for every series." A request holds up to 100,000 series, and a series has up to 10,000 samples.
Write modular_means(totals, counts, p).
totals[i] is the sum of series i. It can be larger than p.counts[i] is the number of samples in series i, from 1 to 10,000.p is a prime number larger than every count.m from 0 to p - 1 with counts[i] × m ≡ totals[i] modulo p.Exactly one such m exists, because p is prime and no count is a multiple of p.
Input: totals = [10, 7, 100], counts = [4, 3, 1], p = 13
Output: [9, 11, 9]| Series | Total | Count | Mean m |
Check: count × m, modulo 13 |
|---|---|---|---|---|
| 0 | 10 | 4 | 9 | 36, which leaves 10 |
| 1 | 7 | 3 | 11 | 33, which leaves 7 |
| 2 | 100 | 1 | 9 | 9, and 100 leaves 9 |
Input: totals = [1, 5000, 0], counts = [2, 10000, 7], p = 10007
Output: [5004, 5004, 0]The mean of 1 over 2 is 5,004, because 2 × 5,004 = 10,008, which leaves 1 modulo 10,007. The mean of 5,000 over 10,000 is the same number.
Input: totals = [8, 3], counts = [2, 6], p = 11
Output: [4, 6]The first mean is the ordinary 8 / 2 = 4. The second is 3 / 6, which is 6 modulo 11, because 6 × 6 = 36 leaves 3.
1 ≤ len(totals) ≤ 100,000, and counts has the same length.0 ≤ totals[i] ≤ 1,000,000,0001 ≤ counts[i] ≤ 10,0007 ≤ p ≤ 1,000,000,007, p is prime, and p is larger than every counts[i].Trying every mean from 0 to p - 1 takes up to 1,000,000,007 tries for one series, and a request holds 100,000 series. Only the 10,000 numbers from 1 to 10,000 can ever be a count. If you know the inverse of each of them, every series is one multiplication. All 10,000 inverses together take 10,000 steps.