Payments app~15 min2s · 256 MBtarget O(q log exp) time, O(log exp) spaceclassic twin: lc-50divide-and-conquer
A payments app runs a savings feature. Each day a balance is multiplied by the same whole-number factor. The ledger keeps every figure modulo a fixed number mod, so the figures stay small.
For an audit, you need the factor after exp days: base to the power exp, modulo mod. Some accounts have run for a billion days.
Your team lead says: Multiplying one day at a time is far too slow. Split the days in half instead.
Write compound_factors(bases, exps, mod).
i, compute bases[i] to the power exps[i], modulo mod.mod fits in a 64-bit integer, so use 64 bits.Input: bases = [3], exps = [10], mod = 1000
Output: [49]The recursion halves the exponent: 10, 5, 2, 1, 0. The calls close in the reverse order, and each row squares the half and adds a factor of 3 when the exponent is odd.
| Call on exponent | Result of the half | Result of this call |
|---|---|---|
| 0 | none: base case | 1 |
| 1 | 1 | 3 |
| 2 | 3 | 9 |
| 5 | 9 | 243 |
| 10 | 243 | 49 |
The last row is the answer: 3 to the power 10 is 59,049, and modulo 1,000 that is 49.
Input: bases = [2, 0, 7], exps = [0, 5, 1], mod = 13
Output: [1, 0, 7]A power of 0 is 1, a base of 0 stays 0, and a power of 1 is the base reduced by mod.
Input: bases = [2, 999999937], exps = [100000, 123456], mod = 998244353
Output: [538261388, 200849119]The exponents are near a hundred thousand. The recursion halves each of them about 17 times.
1 ≤ bases.length = exps.length ≤ 1,0000 ≤ bases[i] ≤ 1,000,000,0000 ≤ exps[i] ≤ 1,000,000,0002 ≤ mod ≤ 1,000,000,000An exponent of 10^9 rules out one multiplication a day: 1,000 accounts would need 10^12 multiplications. The exponent has only 30 bits. Halving it 30 times reaches 0, and the recursion makes 31 calls for 10^9.