Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Karatsuba algorithm

From Wikipedia, the free encyclopedia
Algorithm for integer multiplication
Karatsuba algorithm
ClassMultiplication algorithm
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.

TheKaratsuba algorithm is a fastmultiplication algorithm forintegers. It was discovered byAnatoly Karatsuba in 1960 and published in 1962.[1][2][3] It is adivide-and-conquer algorithm that reduces the multiplication of twon-digit numbers to three multiplications ofn/2-digit numbers and, by repeating this reduction, to at mostnlog23n1.58{\displaystyle n^{\log _{2}3}\approx n^{1.58}} single-digit multiplications. It is thereforeasymptotically faster than thetraditional algorithm, which performsn2{\displaystyle n^{2}} single-digit products.

The Karatsuba algorithm was the first multiplication algorithm asymptotically faster than the quadratic "grade school" algorithm.TheToom–Cook algorithm (1963) is a faster generalization of Karatsuba's method, and theSchönhage–Strassen algorithm (1971) is even faster, for sufficiently largen.

History

[edit]

The standard procedure for multiplication of twon-digit numbers requires a number of elementary operations proportional ton2{\displaystyle n^{2}\,\!}, orO(n2){\displaystyle O(n^{2})\,\!} inbig-O notation.Andrey Kolmogorov conjectured that the traditional algorithm wasasymptotically optimal, meaning that any algorithm for that task would requireΩ(n2){\displaystyle \Omega (n^{2})\,\!} elementary operations.

In 1960, Kolmogorov organized a seminar on mathematical problems incybernetics at theMoscow State University, where he stated theΩ(n2){\displaystyle \Omega (n^{2})\,\!} conjecture and other problems in thecomplexity of computation. Within a week, Karatsuba, then a 23-year-old student, found an algorithm that multiplies twon-digit numbers inO(nlog23){\displaystyle O(n^{\log _{2}3})} 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 theProceedings 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 byYuri 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.[2]

Algorithm

[edit]

Basic step

[edit]

The basic principle of Karatsuba's algorithm isdivide-and-conquer, using a formula that allows one to compute the product of two large numbersx{\displaystyle x} andy{\displaystyle y} using three multiplications of smaller numbers, each with about half as many digits asx{\displaystyle x} ory{\displaystyle y}, plus some additions and digit shifts. This basic step is, in fact, a generalization ofa similar complex multiplication algorithm, where theimaginary uniti is replaced by a power of thebase.

Letx{\displaystyle x} andy{\displaystyle y} be represented asn{\displaystyle n}-digit strings in some baseB{\displaystyle B}. For any positive integerm{\displaystyle m} less thann{\displaystyle n}, one can write the two given numbers as

x=x1Bm+x0,{\displaystyle x=x_{1}B^{m}+x_{0},}
y=y1Bm+y0,{\displaystyle y=y_{1}B^{m}+y_{0},}

wherex0{\displaystyle x_{0}} andy0{\displaystyle y_{0}} are less thanBm{\displaystyle B^{m}}. The product is then

xy=(x1Bm+x0)(y1Bm+y0)=x1y1B2m+(x1y0+x0y1)Bm+x0y0=z2B2m+z1Bm+z0,{\displaystyle {\begin{aligned}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{aligned}}}

where

z2=x1y1,{\displaystyle z_{2}=x_{1}y_{1},}
z1=x1y0+x0y1,{\displaystyle z_{1}=x_{1}y_{0}+x_{0}y_{1},}
z0=x0y0.{\displaystyle z_{0}=x_{0}y_{0}.}

These formulae require four multiplications and were known toCharles Babbage.[4] Karatsuba observed thatxy{\displaystyle xy} can be computed in only three multiplications, at the cost of a few extra additions. Withz0{\displaystyle z_{0}} andz2{\displaystyle z_{2}} as before andz3=(x1+x0)(y1+y0),{\displaystyle z_{3}=(x_{1}+x_{0})(y_{1}+y_{0}),} one can observe that

z1=x1y0+x0y1=(x1+x0)(y0+y1)x1y1x0y0=z3z2z0.{\displaystyle {\begin{aligned}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{aligned}}}

Thus only three multiplications are required for computingz0,z1{\displaystyle z_{0},z_{1}} andz2.{\displaystyle z_{2}.}

Example

[edit]

To compute the product of 12345 and 6789, whereB = 10, choosem = 3. We usem right shifts for decomposing the input operands using the resulting base (Bm =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:

z2 =12×6 = 72
z0 =345×789 = 272205
z1 = (12 +345)× (6 +789) −z2z0 = 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 base1000 as for the input operands):

result =z2 · (Bm)2 +z1 · (Bm)1 +z0 · (Bm)0, i.e.
result = 72 ·10002 + 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.

Recursive application

[edit]

Ifn is four or more, the three multiplications in Karatsuba's basic step involve operands with fewer thann digits. Therefore, those products can be computed byrecursive calls of the Karatsuba algorithm. The recursion can be applied until the numbers are so small that they can (or must) be computed directly.

In a computer with a full 32-bit by 32-bitmultiplier, for example, one could chooseB = 231 and store each digit as a separate 32-bit binary word. Then the sumsx1 +x0 andy1 +y0 will not need an extra binary word for storing the carry-over digit (as incarry-save adder), and the Karatsuba recursion can be applied until the numbers to multiply are only one digit long.

Time complexity analysis

[edit]

Karatsuba's basic step works for any baseB and anym, but the recursive algorithm is most efficient whenm is equal ton/2, rounded up. In particular, ifn is 2k, for some integerk, and the recursion stops only whenn is 1, then the number of single-digit multiplications is 3k, which isnc wherec = log23.

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 anyn, is at most3log2n3nlog23{\displaystyle 3^{\lceil \log _{2}n\rceil }\leq 3n^{\log _{2}3}\,\!}.

Since the additions, subtractions, and digit shifts (multiplications by powers ofB) in Karatsuba's basic step take time proportional ton, their cost becomes negligible asn increases. More precisely, ifT(n) denotes the total number of elementary operations that the algorithm performs when multiplying twon-digit numbers, then

T(n)=3T(n/2)+cn+d{\displaystyle T(n)=3T(\lceil n/2\rceil )+cn+d}

for some constantsc andd. For thisrecurrence relation, themaster theorem for divide-and-conquer recurrences gives theasymptotic boundT(n)=Θ(nlog23){\displaystyle T(n)=\Theta (n^{\log _{2}3})\,\!}.

It follows that, for sufficiently largen, 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 ofn, however, the extra shift and add operations may make it run slower than the longhand method.

Implementation

[edit]

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.[5]

The second argument of the split_at function specifies the number of digits to extract from theright: for example, split_at("12345", 3) will extract the 3 final digits, giving: high="12", low="345".

functionkaratsuba(num1,num2)if(num1<10ornum2<10)returnnum1×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

An issue that occurs when implementation is that the above computation of(x1+x0){\displaystyle (x_{1}+x_{0})} and(y1+y0){\displaystyle (y_{1}+y_{0})} forz1{\displaystyle z_{1}} may result in overflow (will produce a result in the rangeBmresult<2Bm{\displaystyle B^{m}\leq {\text{result}}<2B^{m}}), which require a multiplier having one extra bit. This can be avoided by noting that

z1=(x0x1)(y1y0)+z2+z0.{\displaystyle z_{1}=(x_{0}-x_{1})(y_{1}-y_{0})+z_{2}+z_{0}.}

This computation of(x0x1){\displaystyle (x_{0}-x_{1})} and(y1y0){\displaystyle (y_{1}-y_{0})} will produce a result in the range ofBm<result<Bm{\displaystyle -B^{m}<{\text{result}}<B^{m}}. 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(x0x1){\displaystyle (x_{0}-x_{1})} and(y1y0){\displaystyle (y_{1}-y_{0})} to perform an unsigned multiplication, after which the result may be negated when both signs originally differed. Another advantage is that even though(x0x1)(y1y0){\displaystyle (x_{0}-x_{1})(y_{1}-y_{0})} may be negative, the final computation ofz1{\displaystyle z_{1}} only involves additions.

References

[edit]
  1. ^A. Karatsuba and Yu. Ofman (1962)."Multiplication of Many-Digital Numbers by Automatic Computers".Proceedings of the USSR Academy of Sciences.145:293–294. Translation in the academic journalPhysics-Doklady,7 (1963), pp. 595–596{{cite journal}}: CS1 maint: postscript (link)
  2. ^abA. A. Karatsuba (1995)."The Complexity of Computations"(PDF).Proceedings of the Steklov Institute of Mathematics.211:169–183. Translation from Trudy Mat. Inst. Steklova, 211, 186–202 (1995){{cite journal}}: CS1 maint: postscript (link)
  3. ^ Knuth D.E. (1969)The Art of Computer Programming. v.2. Addison-Wesley Publ.Co., 724 pp.
  4. ^Charles Babbage, Chapter VIII – Of the Analytical Engine, Larger Numbers Treated,Passages from the Life of a Philosopher, Longman Green, London, 1864; page 125.
  5. ^Weiss, Mark A. (2005).Data Structures and Algorithm Analysis in C++. Addison-Wesley. p. 480.ISBN 0321375319.

External links

[edit]
Primality tests
Prime-generating
Integer factorization
Multiplication
Euclideandivision
Discrete logarithm
Greatest common divisor
Modular square root
Other algorithms
  • Italics indicate that algorithm is for numbers of special forms
Retrieved from "https://en.wikipedia.org/w/index.php?title=Karatsuba_algorithm&oldid=1288801081"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp