Skip to content

Commit db95498

Browse files
author
Shivansh
committed
docs: add complexity notes to Strassen algorithm
1 parent 3c88735 commit db95498

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

divide_and_conquer/strassen_matrix_multiplication.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,13 @@ def actual_strassen(matrix_a: list, matrix_b: list) -> list:
7575
"""
7676
Recursive function to calculate the product of two matrices, using the Strassen
7777
Algorithm. It only supports square matrices of any size that is a power of 2.
78+
Complexity:
79+
- Strassen’s algorithm runs in O(n^(log2(7))) ≈ O(n^2.81),
80+
which is asymptotically faster than the classical matrix multiplication
81+
algorithm O(n^3).
82+
- For small matrices, Strassen may be slower due to overhead, so it is
83+
typically beneficial for large n.
84+
7885
"""
7986
if matrix_dimensions(matrix_a) == (2, 2):
8087
return default_matrix_multiplication(matrix_a, matrix_b)
@@ -106,10 +113,20 @@ def actual_strassen(matrix_a: list, matrix_b: list) -> list:
106113

107114
def strassen(matrix1: list, matrix2: list) -> list:
108115
"""
116+
Perform matrix multiplication using Strassen’s algorithm.
117+
118+
Examples:
109119
>>> strassen([[2,1,3],[3,4,6],[1,4,2],[7,6,7]], [[4,2,3,4],[2,1,1,1],[8,6,4,2]])
110120
[[34, 23, 19, 15], [68, 46, 37, 28], [28, 18, 15, 12], [96, 62, 55, 48]]
121+
111122
>>> strassen([[3,7,5,6,9],[1,5,3,7,8],[1,4,4,5,7]], [[2,4],[5,2],[1,7],[5,5],[7,8]])
112123
[[139, 163], [121, 134], [100, 121]]
124+
125+
Complexity Notes:
126+
- Classical matrix multiplication: O(n^3).
127+
- Strassen’s algorithm: O(n^(log2(7))) ≈ O(n^2.81).
128+
- Strassen reduces the number of multiplications from 8 to 7 per recursion,
129+
trading them for additional additions/subtractions.
113130
"""
114131
if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]:
115132
msg = (

0 commit comments

Comments
 (0)