Payments app~25 min2s · 256 MBtarget O(log rounds) time, O(1) spacenumber-theory
A payments app adds a late fee to an overdue invoice in every round of a billing job. In round 0 the fee is 1 unit, and each later round multiplies the previous fee by a fixed factor base. After rounds rounds, the stored penalty is the sum of all fees.
The penalty is stored below a limit modulus, so only the remainder matters. Your team lead asks: "What is the total fee after all the rounds, modulo the limit?" A job can run for up to 10^15 rounds.
Write fee_total(base, rounds, modulus).
base is the factor between one round's fee and the next.rounds is the number of rounds. The fees are base^0, base^1, ..., base^(rounds - 1).modulus is the limit. It need not be a prime number.modulus.Input: base = 3, rounds = 5, modulus = 1000
Output: 121The fees are 1, 3, 9, 27 and 81, and their sum is 121. The code reads the bits of rounds from the top. Each step doubles the stretch of rounds, and a 1 bit adds one more round. The table shows the bits of 5, which is 101.
| Bit of 5 | Bit value | Rounds covered | Total | Power |
|---|---|---|---|---|
| 2 | 1 | 1 | 1 | 3 |
| 1 | 0 | 2 | 4 | 9 |
| 0 | 1 | 5 | 121 | 243 |
Input: base = 1, rounds = 100, modulus = 7
Output: 2With a factor of 1, every fee is 1, so the total is the number of rounds modulo 7.
Input: base = 2, rounds = 20, modulus = 1000003
Output: 48572The total of the fees 1, 2, 4, ..., 2^19 is 2^20 − 1, and the remainder modulo 1,000,003 is shown above.
0 ≤ base ≤ 1,000,000,0001 ≤ rounds ≤ 10^151 ≤ modulus ≤ 1,000,000,000Adding the fees round by round costs one step for each of up to 10^15 rounds, which is far too slow. The bits of rounds number at most 50. Doubling the stretch of rounds 50 times, with one extra round for each 1 bit, costs about 100 steps for any input.