This is a simple implementation of the Karatsuba multiplication algorithm in Verilog. The Karatsuba algorithm has a lower asymptotic complexity than textbook multiplication (in
NB: Fourier-based algorithms are even more efficient asymptotically, with complexities in
Let
Let
The product
This complexity can be reduced by noting that
The product
Let
Let us look for asymptotically exponential solutions, such that
$$
C_m(B) \mathop{\sim}_{B \to \infty} \beta B^\alpha,
$$
where
Since
which is true if and only if
The complexity of the multiplication is thus
The module karatsuba_mul
is defined in the file src/karatsuba_mul.v
.
Parameters:
-
N_BITS
: Number of bits to represent each natural number (also called bit depth). We use a binary little-endian representation. So, if$n$ is a natural integer and$a_0$ ,$a_1$ , ...,$a_n$ are$n+1$ elements of$\lbrace 0, 1 \rbrace$ , the array$[a_0, a_0, \dots, a_n]$ represents the number$\sum_{l=0}^n 2^l , a_l$ . -
MAX_N_BITS_STANDARD_MUL
: Maximum bit depth for which the textbook multiplication algorithm is used instead of the Karatsuba algorithm. This parameter must be at least equal to$3$ . (The algorithm shown above does not work forN_BITS = 3
as$a_0 + a_1$ and$b_0 + b_1$ then also have a bit depth of$3$ , so the algorithm would not terminate.)
Arguments:
a
(input wire, sizeN_BITS
): left inputb
(input wire, sizeN_BITS
): right inputc
(output wire, size2*N_BITS
): product ofa
andb
- Verilator (tested Verilator 5.003 devel rev v5.002-12-g2a3eabff7).
- A C++ compiler compatible with Verilator (tested with g++ 11.3.0).
If you have make
, you may run the test TEST
using the command
make name=TEST test
You may also use directly
verilator --cc --exe --build tests/TEST.cpp tests/TEST.v --top-module TEST
to build the test. The executable will be placed in obj_dir/VTEST
.
The tests currently implemented are:
addition
: a simple test of the addition modulesubtraction
: a simple test of the subtracttion modulemul_2
: multiplication of 2-bit numberskaratsuba_1
: first Karatsuba multiplication test
The command
make all_tests
compiles and runs all the tests.