Karatsuba multiplication
also: divide and conquer multiplication
Multiplying two n-limb integers with three half-size multiplications instead of four, by reusing (a0+a1)(b0+b1) to obtain the middle term. That turns the schoolbook n^2 into about n^1.585, and it only pays above a threshold where the extra additions cost less than the multiplication saved.
Schoolbook multiplication of two -limb integers costs limb products. Split each in half, and , and the product needs four of them:
The middle coefficient is recoverable from the other two plus one extra product, which turns four into three:
Three half-size multiplications and a handful of additions give the recurrence , so
The recursion, with the threshold that makes it worth doing.
let karatsuba_threshold = 32let rec mag_mul a b =if Array.length a < karatsuba_threshold|| Array.length b < karatsuba_threshold then mag_mul_school a belse beginlet k = (max (Array.length a) (Array.length b) + 1) / 2 inlet a0, a1 = split a k and b0, b1 = split b k inlet z0 = mag_mul a0 b0 inlet z2 = mag_mul a1 b1 inlet z1 = mag_sub (mag_sub (mag_mul (mag_add a1 a0) (mag_add b1 b0)) z2) z0 inmag_add (mag_add (mag_shift_limbs z2 (2 * k)) (mag_shift_limbs z1 k)) z0end
The threshold is not a detail. Below it the extra additions and allocations cost more than the multiplication saved, so a Karatsuba implementation without a schoolbook base case is slower than schoolbook on everything anyone actually multiplies. Above a few thousand limbs it is in turn superseded by Toom-Cook and then by FFT-based methods.
referenced by
read more