progress

~/problems / Number theory / Matrix exponentiation

Seed library with donations

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~30 min

A community seed library's stock grows each season: lent packets come back multiplied, older stock is still returning, and a farm donates a fixed batch. So

seeds(0) = a0
seeds(1) = a1
seeds(n) = p · seeds(n-1) + q · seeds(n-2) + r      for n >= 2

Write seeds(a0: int, a1: int, p: int, q: int, r: int, n: int) -> int returning seeds(n) % (10**9 + 7).

seeds(1, 2, 1, 1, 1, 5)    # 20   (1, 2, 4, 7, 12, 20)
seeds(0, 1, 2, 0, 3, 4)    # 29   (0, 1, 5, 13, 29)
seeds(7, 9, 5, 5, 5, 0)    # 7

All inputs are below 10^9 + 7, and n goes up to 10^18, so a season-by-season loop won't finish.

What's new compared with Basics: matrix multiply and matrix power is the constant r, which a plain 2×2 matrix can't add. Carry an extra 1 in the state so the matrix can add r · 1 each step.

⭐ Bonus: a speed test with 20 calls at n near 10^18 earns a star with about 60 matrix products per call.

Show hint

the 3×3 matrix [[p, q, r], [1, 0, 0], [0, 0, 1]] maps [seeds(k), seeds(k-1), 1] to [seeds(k+1), seeds(k), 1]. Raise it to n - 1 by repeated squaring and apply it to [a1, a0, 1].

Topic: Matrix exponentiation. Linear recurrences in O(k^3 log n).

0:00
Ctrl ' run · Ctrl ↵ submit
esc