Matrix Product, Fast Power and Fibonacci Toolkit
Math & Bit ManipulationAuto-graded · 15 test casesLast updated
Combine matrix multiplication, square-and-multiply exponentiation and 2x2 matrix-power Fibonacci, with optional modular arithmetic, in one function.
Write one function that computes three independent quantities and returns them together. An optional modulus can apply to all of them.
Inputs
mat_a: anr × smatrix of integers (list of rows).mat_b: ans × cmatrix of integers (list of rows).base: an integer.exp: a non-negative integer exponent.idx: a non-negative integer index into the Fibonacci sequence.modulus: eitherNone(no reduction) or an integer.
What to compute
-
Matrix product. Compute
mat_a × mat_b, anr × cmatrix, using the standard definition: entry(i, j)is the sum overtofmat_a[i][t] * mat_b[t][j].- If
modulusis given, every entry of the result is reduced modulomodulusinto the range[0, modulus). - If
modulusisNone, entries are left as exact integers. - If
mat_ahas no rows, the product is[]. Ifmat_bhas no rows, treat its column count as 0, so the product haslen(mat_a)rows, each an empty list.
- If
-
Integer power. Compute
base ** expinO(log exp)multiplications.- If
modulusis given, the result isbase ** exp mod modulus, normalized to be non-negative. The one exception isexp = 0, where the answer is always exactly1, even whenmodulus = 1. - If
modulusisNone, return the exact integer, keeping its sign (for example(-2)^3 = -8). 0^0is1.
- If
-
Fibonacci number. Compute
F(idx), whereF(0) = 0,F(1) = 1andF(m) = F(m-1) + F(m-2).- It must run in
O(log idx)matrix operations, soidxcan be as large as10^9when a modulus is supplied. - If
modulusis given, returnF(idx) mod modulus.
- It must run in
Validation
If modulus is not None and is <= 0, raise ValueError before doing any other work.
Output
Return a dictionary with exactly these keys:
"matrix": the product from part 1,"power": the value from part 2,"fib": the value from part 3.
Constraints
mat_a[i]has lengthsfor every row, andmat_bhassrows of equal length, so the product is well defined.exp >= 0andidx >= 0.- Matrix entries and
baseare integers that may be negative. - When
modulusisNone, inputs are small enough that exact results are practical. - When
modulusis given, it may be as large as about10^9 + 7, andidxandexpmay be as large as10^9.
Examples
Example 1
Input: matrix_pow_fib_toolkit([[1, 2], [3, 4]], [[5, 6], [7, 8]], 2, 10, 10, None)
Output: {'matrix': [[19, 22], [43, 50]], 'power': 1024, 'fib': 55}
Example 2
Input: matrix_pow_fib_toolkit([[1, 2, 3], [4, 5, 6]], [[7, 8], [9, 10], [11, 12]], 3, 0, 0, 1000000007)
Output: {'matrix': [[58, 64], [139, 154]], 'power': 1, 'fib': 0}
Example 3
Input: matrix_pow_fib_toolkit([[2]], [[3]], 0, 5, 1, 7)
Output: {'matrix': [[6]], 'power': 0, 'fib': 1}
Hints
Hint 1
Treat the three tasks separately. The matrix product is three nested loops: for each output cell, sum the products along the shared dimension, reducing modulo `modulus` if one is given.
Hint 2
For the power, look at `exp` in binary. Keep a running square of the base, multiply it into the answer whenever the lowest bit of the exponent is 1, then shift the exponent right.
Hint 3
Fibonacci can be written as repeated multiplication by the matrix [[1,1],[1,0]]. Raise it to the power `idx` with the same square-and-multiply loop, starting from the identity matrix, and read `F(idx)` from the top-right entry.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function does three independent jobs, and the third reuses the idea of the second.
Matrix product. For each output cell (i, j), add up mat_a[i][t] * mat_b[t][j] over the shared dimension t. The loop order i, t, j reads one value from mat_a and then sweeps a row of mat_b. If a modulus is given, reduce after each accumulation so numbers stay small and results land in [0, modulus).
Fast power. Write exp in binary. Then base^exp is the product of base^(2^i) over the set bits i. Keep a running value that is squared on every step, multiply it into the answer when the lowest bit of the remaining exponent is 1, and shift the exponent right. The answer starts at 1 and is only reduced after a multiplication, so exp = 0 returns exactly 1, even with modulus = 1. The base is reduced first when a modulus exists, which also normalizes negative bases.
Fibonacci. Since [F(m+1), F(m); F(m), F(m-1)] = [[1,1],[1,0]]^m, we can raise that 2x2 matrix to the power idx with the same square-and-multiply loop, using the identity matrix in place of 1 and matrix multiplication in place of *. The top-right entry of the result is F(idx). For idx = 0 the loop never runs and the identity gives 0.
The modulus is validated first, so an invalid value raises ValueError before any work.
Why it is correct
- Product: each cell receives exactly one term per shared index, which is the definition. Reducing after each addition is valid because modular reduction commutes with addition and multiplication.
- Power: the loop keeps the invariant
acc * b^e = base^exp. It holds at the start. Moving one factor ofbintoaccwhen the low bit is 1 preserves it, and squaringbwhile halvingepreserves it. Whene = 0,accis the answer. - Fibonacci: by induction, multiplying
Q^mbyQshifts the pair(F(m+1), F(m))to(F(m+2), F(m+1)). Matrix multiplication is associative, so the squaring argument works exactly as for scalars.
Complexity
- Matrix product:
O(r * s * c)time,O(r * c)space. - Power:
O(log exp)multiplications,O(1)extra space. - Fibonacci:
O(log idx)multiplications of 2x2 matrices (8 scalar multiplications each),O(1)space. With a modulus all operands stay belowmodulus, so this is truly logarithmic. Without one, the numbers grow to about0.694 * idxbits.
Reference solution
from typing import Dict, List, Optional
def matrix_pow_fib_toolkit(mat_a: List[List[int]], mat_b: List[List[int]], base: int, exp: int, idx: int, modulus: Optional[int] = None) -> Dict[str, object]:
if modulus is not None and modulus <= 0:
raise ValueError('modulus must be positive')
def mat_mul(left, right):
rows = len(left)
shared = len(right)
cols = len(right[0]) if right else 0
out = [[0] * cols for _ in range(rows)]
for i in range(rows):
for t in range(shared):
v = left[i][t]
for j in range(cols):
out[i][j] += v * right[t][j]
if modulus is not None:
out[i][j] %= modulus
return out
def fast_pow(b, e):
acc = 1
if modulus is not None:
b %= modulus
while e:
if e & 1:
acc *= b
if modulus is not None:
acc %= modulus
b *= b
if modulus is not None:
b %= modulus
e >>= 1
return acc
product = mat_mul(mat_a, mat_b)
power_value = fast_pow(base, exp)
step = [[1, 1], [1, 0]]
acc = [[1, 0], [0, 1]]
e = idx
while e:
if e & 1:
acc = mat_mul(acc, step)
step = mat_mul(step, step)
e >>= 1
fib_value = acc[0][1]
if modulus is not None:
fib_value %= modulus
return {'matrix': product, 'power': power_value, 'fib': fib_value}