Karatsuba algorithm: Difference between revisions

Content deleted Content added
No edit summary
integer specify in lead
 
(397 intermediate revisions by more than 100 users not shown)
Line 1:
{{short description|Algorithm for integer multiplication}}
The '''Karatsuba''' [[multiplication algorithm]], a technique for quickly multiplying large numbers, was discovered by Anatolii Alexeevich Karatsuba in 1960 and published together with Yu. Ofman in 1962. Its [[time complexity]] is [[Big O notation|Θ]]<math>(n^{\log_23})</math>. This makes it faster than the [[long multiplication|classical]] Θ(''n''<sup>2</sup>) algorithm (<math>\log_23 \approx 1.585</math>).
{{Infobox algorithm
|class = [[Multiplication algorithm]]
|image = <!-- filename only, no "File:" or "Image:" prefix, and no enclosing [[brackets]] -->
|caption =
|data =
|time = <!-- Worst time big-O notation -->
|best-time =
|average-time =
|space = <!-- Worst-case space complexity; auxiliary space
(excluding input) if not specified -->
}}
[[File:Karatsuba_multiplication.svg|thumb|300px|Karatsuba multiplication of az+b and cz+d (boxed), and 1234 and 567 with z=100. Magenta arrows denote multiplication, amber denotes addition, silver denotes subtraction and cyan denotes left shift. (A), (B) and (C) show recursion with z=10 to obtain intermediate values.]]
The '''Karatsuba algorithm''' is a fast [[multiplication algorithm]] for [[Integer|integers]]. It was discovered by [[Anatoly Karatsuba]] in 1960 and published in 1962.<ref name="kara1962">
{{cite journal
| author = A. Karatsuba and Yu. Ofman
| title = Multiplication of Many-Digital Numbers by Automatic Computers
| journal = Proceedings of the USSR Academy of Sciences
| volume = 145
| year = 1962
| pages = 293–294
| url = https://www.mathnet.ru/php/archive.phtml?wshow=paper&jrnid=dan&paperid=26729&option_lang=eng
| postscript = . Translation in the academic journal ''[[Physics-Doklady]]'', '''7''' (1963), pp. 595–596}}
</ref><ref name="kara1995">
{{cite journal
| author = A. A. Karatsuba
| title = The Complexity of Computations
| journal = Proceedings of the Steklov Institute of Mathematics
| volume = 211
| pages =169–183
| year = 1995
| url = http://www.ccas.ru/personal/karatsuba/divcen.pdf
| postscript = . Translation from Trudy Mat. Inst. Steklova, 211, 186–202 (1995)}}
</ref><ref name="knuthV2">
Knuth D.E. (1969) ''[[The Art of Computer Programming]]. v.2.'' Addison-Wesley Publ.Co., 724 pp.
</ref> It is a [[divide-and-conquer algorithm]] that reduces the multiplication of two ''n''-digit numbers to three multiplications of ''n''/2-digit numbers and, by repeating this reduction, to at most <math> n^{\log_23}\approx n^{1.58}</math> single-digit multiplications. It is therefore [[Asymptotic complexity|asymptotically faster]] than the [[long multiplication|traditional]] algorithm, which performs <math>n^2</math> single-digit products.
 
The Karatsuba algorithm was the first multiplication algorithm asymptotically faster than the quadratic "grade school" algorithm.
The [[Toom–Cook multiplication|Toom–Cook algorithm]] (1963) is a faster generalization of Karatsuba's method, and the [[Schönhage–Strassen algorithm]] (1971) is even faster, for sufficiently large ''n''.
 
==History==
The standard procedure for multiplication of two ''n''-digit numbers requires a number of elementary operations proportional to <math>n^2\,\!</math>, or <math>O(n^2)\,\!</math> in [[big-O notation]]. [[Andrey Kolmogorov]] conjectured that the traditional algorithm was ''[[asymptotically optimal]],'' meaning that any algorithm for that task would require <math>\Omega(n^2)\,\!</math> elementary operations.
 
In 1960, Kolmogorov organized a seminar on mathematical problems in [[cybernetics]] at the [[Moscow State University]], where he stated the <math>\Omega(n^2)\,\!</math> conjecture and other problems in the [[Computational complexity theory|complexity of computation]]. Within a week, Karatsuba, then a 23-year-old student, found an algorithm that multiplies two ''n''-digit numbers in <math>O(n^{\log_2 3})</math> elementary steps, thus disproving the conjecture. Kolmogorov was very excited about the discovery; he communicated it at the next meeting of the seminar, which was then terminated. Kolmogorov gave some lectures on the Karatsuba result at conferences all over the world (see, for example, "Proceedings of the International Congress of Mathematicians 1962", pp. 351–356, and also "6 Lectures delivered at the International Congress of Mathematicians in Stockholm, 1962") and published the method in 1962, in the [[Proceedings of the USSR Academy of Sciences]]. The article had been written by Kolmogorov and contained two results on multiplication, Karatsuba's algorithm and a separate result by [[Yuri Petrovich Ofman|Yuri Ofman]]; it listed "A. Karatsuba and Yu. Ofman" as the authors. Karatsuba only became aware of the paper when he received the reprints from the publisher.<ref name="kara1995"/>
 
==Algorithm==
The speed of this algorithm relies partly on the ability to do [[arithmetic shift|shift]]s faster than a standard multiply, with shifts typically taking [[linear time]] on a practical computer.
 
===Basic step===
We assume two ''n''-digit numbers ''x'' and ''y'', represented in [[radix|base]] ''B'' where ''B'' is a convenient value to shift with, like two in modern binary computers. Choosing a number ''m'' less than ''n'', we can write
The basic principle of Karatsuba's algorithm is [[Divide-and-conquer algorithm|divide-and-conquer]], using a formula that allows one to compute the product of two large numbers <math>x</math> and <math>y</math> using three multiplications of smaller numbers, each with about half as many digits as <math>x</math> or <math>y</math>, plus some additions and digit shifts. This basic step is, in fact, a generalization of [[Multiplication algorithm#Complex number multiplication|a similar complex multiplication algorithm]], where the [[imaginary unit]] {{mvar|i}} is replaced by a power of the [[radix|base]].
 
Let <math>x</math> and <math>y</math> be represented as <math>n</math>-digit strings in some base <math>B</math>. For any positive integer <math>m</math> less than <math>n</math>, one can write the two given numbers as
:''x'' = ''x''<sub>1</sub>''B''<sup>''m''</sup> + ''x''<sub>2</sub>
:''y'' = ''y''<sub>1</sub>''B''<sup>''m''</sup> + ''y''<sub>2</sub>
 
:<math>x = x_1 B^m + x_0,</math>
where ''x''<sub>2</sub> and ''y''<sub>2</sub> are less than ''B''<sup>''m''</sup>; it is easily seen that there is a unique representation. We now have
:<math>y = y_1 B^m + y_0,</math>
 
where <math>x_0</math> and <math>y_0</math> are less than <math>B^m</math>. The product is then
:''xy'' = (''x''<sub>1</sub>''B''<sup>''m''</sup> + ''x''<sub>2</sub>)(''y''<sub>1</sub>''B''<sup>''m''</sup> + ''y''<sub>2</sub>)
::= ''x''<sub>1</sub>''y''<sub>1</sub>''B''<sup>2''m''</sup> + (''x''<sub>1</sub>''y''<sub>2</sub> + ''x''<sub>2</sub>''y''<sub>1</sub>)''B''<sup>''m''</sup> + ''x''<sub>2</sub>''y''<sub>2</sub>
 
<math>
The standard method is to multiply the four subproducts separately, then finally shift and add; this is O(n<sup>2</sup>). However, Karatsuba observed that we can compute ''xy'' in only three multiplications:
\begin{align}
xy &= (x_1 B^m + x_0)(y_1 B^m + y_0) \\
&= x_1 y_1 B^{2m} + (x_1 y_0 + x_0 y_1) B^m + x_0 y_0 \\
&= z_2 B^{2m} + z_1 B^m + z_0, \\
\end{align}
</math>
 
where
:Let ''X'' = ''x''<sub>1</sub>''y''<sub>1</sub>
:Let ''Y'' = ''x''<sub>2</sub>''y''<sub>2</sub>
:Let ''Z'' = (''x''<sub>1</sub> + ''x''<sub>2</sub>)(''y''<sub>1</sub> + ''y''<sub>2</sub>) - X - Y
 
:<math>z_2 = x_1 y_1,</math>
We note that
:<math>z_1 = x_1 y_0 + x_0 y_1,</math>
:<math>z_0 = x_0 y_0.</math>
 
These formulae require four multiplications and were known to [[Charles Babbage]].<ref>Charles Babbage, Chapter VIII – Of the Analytical Engine, Larger Numbers Treated, [https://archive.org/details/bub_gb_Fa1JAAAAMAAJ/page/n142 <!-- pg=125 --> Passages from the Life of a Philosopher], Longman Green, London, 1864; page 125.</ref> Karatsuba observed that <math>xy</math> can be computed in only three multiplications, at the cost of a few extra additions. With <math>z_0</math> and <math>z_2</math> as before and <math>z_3=(x_1 + x_0) (y_1 + y_0),</math> one can observe that
:''Z'' = (''x''<sub>1</sub>''y''<sub>1</sub> + ''x''<sub>1</sub>''y''<sub>2</sub> + ''x''<sub>2</sub>''y''<sub>1</sub> + ''x''<sub>2</sub>''y''<sub>2</sub>) - ''x''<sub>1</sub>''y''<sub>1</sub> - ''x''<sub>2</sub>''y''<sub>2</sub>
:<math>
::= ''x''<sub>1</sub>''y''<sub>2</sub> + ''x''<sub>2</sub>''y''<sub>1</sub>
\begin{align}
z_1 &= x_1 y_0 + x_0 y_1 \\
&= (x_1 + x_0) (y_0 + y_1) - x_1 y_1 - x_0 y_0 \\
&= z_3 - z_2 - z_0. \\
\end{align}
</math>
 
Thus only three multiplications are required for computing <math>z_0, z_1</math> and <math>z_2.</math>
Thus ''xy'' = ''X'' ''B''<sup>2m</sup> + ''Y'' + ''Z'' ''B''<sup>m</sup>; we have cut down the number of multiplications from four to three.
 
===Example===
To compute these three products of ''m''-digit numbers, we can [[recursion|recursively]] employ Karatsuba multiplication again. The shifts, additions and subtractions take linear time respectively, and can be considered negligible.
To compute the product of 12345 and 6789, where ''B'' = 10, choose ''m'' = 3. We use ''m'' right shifts for decomposing the input operands using the resulting base (''B''<sup>''m''</sup> = ''1000''), as:
: 12345 = '''12''' · ''1000'' + '''345'''
: 6789 = '''6''' · ''1000'' + '''789'''
 
Only three multiplications, which operate on smaller integers, are used to compute three partial results:
Karatsuba multiplication works best when the two operands are of similar size; thus while one can theoretically choose ''m'' arbitrarily, the best time bound would be achieved by choosing ''m'' such that the subproducts are roughly equal, that is setting ''m'' to be about ''n''/2.
: ''z''<sub>2</sub> = '''12''' '''×''' '''6''' = 72
: ''z''<sub>0</sub> = '''345''' '''×''' '''789''' = 272205
: ''z''<sub>1</sub> = ('''12''' + '''345''') '''×''' ('''6''' + '''789''') − ''z''<sub>2</sub> − ''z''<sub>0</sub> = 357 '''×''' 795 − 72 − 272205 = 283815 − 72 − 272205 = 11538
 
We get the result by just adding these three partial results, shifted accordingly (and then taking carries into account by decomposing these three inputs in base ''1000'' as for the input operands):
==Example==
: result = ''z''<sub>2</sub> · (''B''<sup>''m''</sup>)<sup>''2''</sup> + ''z''<sub>1</sub> · (''B''<sup>''m''</sup>)<sup>''1''</sup> + ''z''<sub>0</sub> · (''B''<sup>''m''</sup>)<sup>''0''</sup>, i.e.
Say we want to compute the product of 1234 and 5678. We choose ''B'' = 10 and ''m'' = 2. We have
: result = 72 · ''1000''<sup>2</sup> + 11538 · ''1000'' + 272205 = '''83810205'''.
 
Note that the intermediate third multiplication operates on an input ___domain which is less than two times larger than for the two first multiplications, its output ___domain is less than four times larger, and base-''1000'' carries computed from the first two multiplications must be taken into account when computing these two subtractions.
:12 34 = 12 &sdot; 10<sup>2</sup> + 34
:56 78 = 56 &sdot; 10<sup>2</sup> + 78
:''X'' = 12 &sdot; 56 = 672
:''Y'' = 34 &sdot; 78 = 2652
:''Z'' = (12 + 34)(56 + 78) - ''X'' - ''Y'' = 46 &sdot; 134 - 672 - 2652 = 2840
:''X'' 10<sup>2&sdot;2</sup> + ''Y'' + ''Z'' 10<sup>2</sup> = 672 0000 + 2652 + 2840 00 = '''7006652''' = 1234 &sdot; 5678
 
===Recursive application===
==Complexity==
If ''n'' is four or more, the three multiplications in Karatsuba's basic step involve operands with fewer than ''n'' digits. Therefore, those products can be computed by [[recursion|recursive]] calls of the Karatsuba algorithm. The recursion can be applied until the numbers are so small that they can (or must) be computed directly.
If ''T''(''n'') denotes the time it takes to multiply two ''n''-digit numbers with Karatsuba's method, then we can write
 
In a computer with a full 32-bit by 32-bit [[Binary multiplier|multiplier]], for example, one could choose ''B'' = 2<sup>31</sup> and store each digit as a separate 32-bit binary word. Then the sums ''x''<sub>1</sub> + ''x''<sub>0</sub> and ''y''<sub>1</sub> + ''y''<sub>0</sub> will not need an extra binary word for storing the carry-over digit (as in [[carry-save adder]]), and the Karatsuba recursion can be applied until the numbers to multiply are only one digit long.
:''T''(''n'') = 3 ''T''(''n''/2) + ''cn'' + ''d''
 
===[[Time complexity]] analysis===
for some constants ''c'' and ''d'', and this [[recurrence relation]] can be solved using the [[master theorem]], giving a time complexity of Θ(''n''<sup>log(3)/log(2)</sup>). The number log(3)/log(2) is approximately 1.585, so this method is significantly faster than [[long multiplication]] as ''n'' grows large. Because of the overhead of recursion, however, Karatsuba's multiplication is typically slower than long multiplication for small values of ''n''; typical implementations therefore switch to long multiplication if ''n'' is below some threshold when computing the subproducts.
Karatsuba's basic step works for any base ''B'' and any ''m'', but the recursive algorithm is most efficient when ''m'' is equal to ''n''/2, rounded up. In particular, if ''n'' is 2<sup>''k''</sup>, for some integer ''k'', and the recursion stops only when ''n'' is 1, then the number of single-digit multiplications is 3<sup>''k''</sup>, which is ''n''<sup>''c''</sup> where ''c'' = log<sub>2</sub>3.
 
Since one can extend any inputs with zero digits until their length is a power of two, it follows that the number of elementary multiplications, for any ''n'', is at most <math>3^{ \lceil\log_2 n \rceil} \leq 3 n^{\log_2 3}\,\!</math>.
Implementations differ greatly on what the crossover point is when Karatsuba becomes faster than the classical algorithm, but generally numbers over 2<sup>320</sup> are faster with Karatsuba. [http://gmplib.org/manual/Karatsuba-Multiplication.html][http://ozark.hendrix.edu/~burch/proj/karat/comment1.html] [[Toom-Cook multiplication]] is a faster generalization of Karatsuba's, and is further surpassed by the fastest known, the [[Schönhage-Strassen algorithm]].
 
Since the additions, subtractions, and digit shifts (multiplications by powers of ''B'') in Karatsuba's basic step take time proportional to ''n'', their cost becomes negligible as ''n'' increases. More precisely, if ''T''(''n'') denotes the total number of elementary operations that the algorithm performs when multiplying two ''n''-digit numbers, then
 
:<math>T(n) = 3 T(\lceil n/2\rceil) + cn + d</math>
 
for some constants ''c'' and ''d''. For this [[recurrence relation]], the [[master theorem (analysis of algorithms)|master theorem for divide-and-conquer recurrences]] gives the [[big O notation|asymptotic]] bound <math>T(n) = \Theta(n^{\log_2 3})\,\!</math>.
 
It follows that, for sufficiently large ''n'', Karatsuba's algorithm will perform fewer shifts and single-digit additions than longhand multiplication, even though its basic step uses more additions and shifts than the straightforward formula. For small values of ''n'', however, the extra shift and add operations may make it run slower than the longhand method.
 
==Implementation==
 
Here is the pseudocode for this algorithm, using numbers represented in base ten. For the binary representation of integers, it suffices to replace everywhere 10 by 2.<ref>{{cite book |last= Weiss |first= Mark A. |date= 2005 |title= Data Structures and Algorithm Analysis in C++ |publisher= Addison-Wesley|page= 480|isbn= 0321375319}}</ref>
 
The second argument of the split_at function specifies the number of digits to extract from the ''right'': for example, split_at("12345", 3) will extract the 3 final digits, giving: high="12", low="345".
 
<syntaxhighlight lang="c">
function karatsuba(num1, num2)
if (num1 < 10 or num2 < 10)
return num1 × num2 /* fall back to traditional multiplication */
/* Calculates the size of the numbers. */
m = max(size_base10(num1), size_base10(num2))
m2 = floor(m / 2)
/* m2 = ceil (m / 2) will also work */
/* Split the digit sequences in the middle. */
high1, low1 = split_at(num1, m2)
high2, low2 = split_at(num2, m2)
/* 3 recursive calls made to numbers approximately half the size. */
z0 = karatsuba(low1, low2)
z1 = karatsuba(low1 + high1, low2 + high2)
z2 = karatsuba(high1, high2)
return (z2 × 10 ^ (m2 × 2)) + ((z1 - z2 - z0) × 10 ^ m2) + z0
</syntaxhighlight>
 
An issue that occurs when implementation is that the above computation of <math>(x_1 + x_0)</math> and <math>(y_1 + y_0)</math> for <math>z_1</math> may result in overflow (will produce a result in the range <math>B^m \leq \text{result} < 2 B^m</math>), which require a multiplier having one extra bit. This can be avoided by noting that
 
:<math>z_1 = (x_0 - x_1)(y_1 - y_0) + z_2 + z_0.</math>
 
This computation of <math>(x_0 - x_1)</math> and <math>(y_1 - y_0)</math> will produce a result in the range of <math>-B^m < \text{result} < B^m</math>. This method may produce negative numbers, which require one extra bit to encode signedness, and would still require one extra bit for the multiplier. However, one way to avoid this is to record the sign and then use the absolute value of <math>(x_0 - x_1)</math> and <math>(y_1 - y_0)</math> to perform an unsigned multiplication, after which the result may be negated when both signs originally differed. Another advantage is that even though <math>(x_0 - x_1)(y_1 - y_0)</math> may be negative, the final computation of <math>z_1</math> only involves additions.
 
==References==
{{Reflist}}
* A. Karatsuba and Yu Ofman, "Multiplication of Many-Digital Numbers by Automatic Computers." ''Doklady Akad. Nauk SSSR'' Vol. 145 (1962), pp. 293&ndash;294. Translation in ''Physics-Doklady'' 7 (1963), pp. 595&ndash;596.
 
* Karatsuba A. A. The complexity of computations // Proc. Steklov Inst. Math., 211, 169–183 (1995); translation from Trudy Mat. Inst. Steklova, 211, 186–202 (1995).
==External links==
*[http://mathworld.wolfram.com/KaratsubaMultiplication.html Karatsuba Multiplication on MathWorld]
* [http://www.cs.pitt.edu/~kirk/cs1501/animations/Karatsuba.html Karatsuba's Algorithm for Polynomial Multiplication]
*Bernstein, D. J., "[http://cr.yp.to/papers/m3.pdf Multidigit multiplication for mathematicians]". Covers Karatsuba and many other multiplication algorithms.
*{{MathWorld|urlname=KaratsubaMultiplication|title=Karatsuba Multiplication}}
[[Category:Arbitrary precision algorithms]]
* Bernstein, D. J., "[http://cr.yp.to/papers/m3.pdf Multidigit multiplication for mathematicians]". Covers Karatsuba and many other multiplication algorithms.
* [http://www.ccas.ru/personal/karatsuba/divcen.htm Karatsuba Multiplication on Fast Algorithms and the FEE]
 
{{Number-theoretic algorithms}}
 
[[Category:Computer arithmetic algorithms]]
[[de:Karatsuba-Algorithmus]]
[[Category:Multiplication]]
[[fr:Algorithme de Karatsuba]]
[[Category:Articles with example pseudocode]]
[[it:Algoritmo di Karatsuba]]
[[Category:Divide-and-conquer algorithms]]
[[pl:Algorytm Karatsuby]]