<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Karatsuba algorithm &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/karatsuba-algorithm/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Karatsuba Fast Multiplication</title>
		<link>/2012/05/15/computer-algorithms-karatsuba-fast-multiplication/</link>
		<comments>/2012/05/15/computer-algorithms-karatsuba-fast-multiplication/#comments</comments>
		<pubDate>Tue, 15 May 2012 19:52:59 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Anatolii Alexeevitch Karatsuba]]></category>
		<category><![CDATA[Andrey Kolmogorov]]></category>
		<category><![CDATA[Cohen-Sutherland]]></category>
		<category><![CDATA[Divide and conquer algorithm]]></category>
		<category><![CDATA[Karatsuba algorithm]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Multiplication]]></category>
		<category><![CDATA[Multiplication algorithm]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[structured algorithm]]></category>

		<guid isPermaLink="false">/?p=3121</guid>
		<description><![CDATA[Introduction Typically multiplying two n-digit numbers require n2 multiplications. That is actually how we, humans, multiply numbers. Let’s take a look of an example in case we’ve to multiply two 2-digit numbers. 12 x 15 = ? OK, we know that the answer is 180 and there are lots of intuitive methods that help us &#8230; <a href="/2012/05/15/computer-algorithms-karatsuba-fast-multiplication/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Karatsuba Fast Multiplication</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2013/01/14/computer-algorithms-multiplication/" rel="bookmark" title="Computer Algorithms: Multiplication">Computer Algorithms: Multiplication </a></li>
<li><a href="/2012/11/26/computer-algorithms-strassens-matrix-multiplication/" rel="bookmark" title="Computer Algorithms: Strassen&#8217;s Matrix Multiplication">Computer Algorithms: Strassen&#8217;s Matrix Multiplication </a></li>
<li><a href="/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/" rel="bookmark" title="Computer Algorithms: Determine if a Number is Prime">Computer Algorithms: Determine if a Number is Prime </a></li>
<li><a href="/2012/12/24/computer-algorithms-sorting-in-linear-time/" rel="bookmark" title="Computer Algorithms: Sorting in Linear Time">Computer Algorithms: Sorting in Linear Time </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Typically multiplying two n-digit numbers require n<sup>2</sup> multiplications. That is actually how we, humans, multiply numbers. Let’s take a look of an example in case we’ve to multiply two 2-digit numbers.</p>
<pre lang="php">12 x 15 = ?</pre>
<p>OK, we know that the answer is 180 and there are lots of intuitive methods that help us get the right answer. Indeed 12 x 15 it’s just a bit more difficult to calculate than 10 x 15, because multiplying by 10 it really easy &#8211; we just add one 0 at the end of the number. Thus 15 x 10 equals 150. But now again on 12 x 15 &#8211; we know that this equals 10 x 15 (which is 150) and 2 x 15, which is also very easy to calculate and it is 30. The result of 12&#215;15 will be 150 + 30, which fortunately isn’t difficult to get and equals to 180.</p>
<p>That was easy but in some cases the calculations are a bit more difficult and we need a structured algorithm to get the right answer. What about 65 x 97? That is not so easy as 12 x 15, right?</p>
<p>The algorithm we know from the primary school, described on the diagram below, is well structured and help us multiply two numbers.</p>
<div class="mceTemp">
<dl id="attachment_3139" class="wp-caption alignnone" style="width: 494px;">
<dt class="wp-caption-dt"><a href="/wp-content/uploads/2012/05/1.-Typical-Multiplication.png"><img class="size-full wp-image-3139" title="Typical Multiplication" src="/wp-content/uploads/2012/05/1.-Typical-Multiplication.png" alt="Typical Multiplication" width="484" height="518" srcset="/wp-content/uploads/2012/05/1.-Typical-Multiplication.png 484w, /wp-content/uploads/2012/05/1.-Typical-Multiplication-280x300.png 280w" sizes="(max-width: 484px) 100vw, 484px" /></a></dt>
<dd class="wp-caption-dd"></dd>
</dl>
</div>
<p>We see that even for two-digit numbers this is quite difficult &#8211; we have 4 multiplications and some additions.<span id="more-3121"></span></p>
<figure id="attachment_3143" style="width: 484px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/2.-Number-of-Multiplications.png"><img src="/wp-content/uploads/2012/05/2.-Number-of-Multiplications.png" alt="Number of Multiplications" title="Number of Multiplications" width="484" height="518" class="size-full wp-image-3143" srcset="/wp-content/uploads/2012/05/2.-Number-of-Multiplications.png 484w, /wp-content/uploads/2012/05/2.-Number-of-Multiplications-280x300.png 280w" sizes="(max-width: 484px) 100vw, 484px" /></a><figcaption class="wp-caption-text">We need 4 multiplications in order to calculate the product of two 2-digit numbers!</figcaption></figure>
<p>However so far we know how to multiply numbers, the only problem is that our task becomes very difficult as the numbers grow. If multiplying 65 by 97 was somehow easy, what about</p>
<pre lang="php">374773294776321
x
222384759707982</pre>
<p>It seems almost impossible.</p>
<h3>History</h3>
<p><a title="Andrey Kolmogorov" href="http://en.wikipedia.org/wiki/Andrey_Kolmogorov" target="_blank">Andrey Kolmogorov</a> is one of the brightest russian mathematicians of the 20th century. In 1960, during a seminar, Kolmogorov stated that two n-digit numbers can’t be multiplied with less than n<sup>2</sup> multiplications!<br />
Only a week later a 23-year young student called <a title="Anatolii Alexeevitch Karatsuba" href="http://en.wikipedia.org/wiki/Anatolii_Alexeevitch_Karatsuba" target="_blank">Anatolii Alexeevitch Karatsuba</a> proved that the multiplication of two n-digit numbers can be computed with n ^ lg(3) multiplications with an ingenious divide and conquer approach.</p>
<h2>Overview</h2>
<p>Basically Karatsuba stated that if we have to multiply two n-digit numbers x and y, this can be done with the following operations, assuming that B is the base of and m &lt; n.</p>
<p>First both numbers x and y can be represented as x1,x2 and y1,y2 with the following formula.</p>
<pre lang="PHP">
x = x1 * B^m + x2 
y = y1 * B^m + y2 
</pre>
<p>Obviously now xy will become as the following product.</p>
<pre lang="PHP">
xy = (x1 * B^m + x2)(y1 * B^m + y2) =>

a = x1 * y1
b = x1 * y2 + x2 * y1
c = x2 * y2
</pre>
<p>Finally xy will become:</p>
<pre lang="PHP">
xy = a * B^2m + b * B^m + c
</pre>
<p>However a, b and c can be computed at least with four multiplication, which isn’t a big optimization. That is why Karatsuba came up with the brilliant idea to calculate b with the following formula:</p>
<pre lang="PHP">
b = (x1 + x2)(y1 + y2) - a - c
</pre>
<p>That make use of only three multiplications to get xy.</p>
<p>Let’s see this formula by example. </p>
<pre lang="PHP">
47 x 78

x = 47
x = 4 * 10 + 7

x1 = 4
x2 = 7

y = 78
y = 7 * 10 + 8

y1 = 7
y2 = 8

a = x1 * y1 = 4 * 7 = 28
c = x2 * y2 = 7 * 8 = 56
b = (x1 + x2)(y1 + y2) - a - c = 11 * 15 - 28 - 56
</pre>
<p>Now the thing is that 11 * 15 it’s again a multiplication between 2-digit numbers, but fortunately we can apply the same rules two them. This makes the algorithm of Karatsuba a perfect example of the “divide and conquer” algorithm.</p>
<h2>Implementation</h2>
<h3>Standard Multiplication</h3>
<p>Typically the standard implementation of multiplication of n-digit numbers require n<sup>2</sup> multiplications as you can see from the following <a href="/category/php/" title="PHP on stoimen.com">PHP</a> implementation.</p>
<pre lang="PHP">
$x = array(1,2,3,4);
$y = array(5,6,7,8);

function multiply($x, $y)
{	
	$len_x = count($x);
	$len_y = count($y);
	$half_x = ceil($len_x / 2);
	$half_y = ceil($len_y / 2);
	$base = 10;

	// bottom of the recursion
	if ($len_x == 1 && $len_y == 1) {
		return $x[0] * $y[0];
	}
	
	$x_chunks = array_chunk($x, $half_x);
	$y_chunks = array_chunk($y, $half_y);
	
	// predefine aliases
	$x1 = $x_chunks[0];
	$x2 = $x_chunks[1];
	$y1 = $y_chunks[0];
	$y2 = $y_chunks[1];
	
	return  multiply($x1, $y1) * pow($base, $half_x * 2) 					// a
		 	+ (multiply($x1, $y2) + multiply($x2, $y1)) * pow($base, $half_x) 	// b
		 	+ multiply($x2, $y2);							// c
}

// 7 006 652
echo multiply($x, $y);
</pre>
<h3>Karatsuba Multiplication</h3>
<p>Karatsuba replaces two of the multiplications &#8211; this of x1 * y2 + x2 * y1 with only one &#8211; (x1 + x2)(y1 + y2) and this makes the algorithm faster.</p>
<pre lang="PHP">
$x = array(1,2,3,4);
$y = array(5,6,7,8);

function karatsuba($x, $y) 
{
	$len_x = count($x);
	$len_y = count($y);
	
	// bottom of the recursion
	if ($len_x == 1 && $len_y == 1) {
		return $x[0] * $y[0];
	} 
	if ($len_x == 1 || $len_y == 1) {
		$t1 = implode('', $x);
		$t2 = implode('', $y);
		return (int)$t1 * $t2;
	}
	
	$a = array_chunk($x, ceil($len_x/2));
	$b = array_chunk($y, ceil($len_y/2));
	
	$deg = floor($len_x/2);
	
	$x1 = $a[0];	// 1
	$x2 = $a[1];	// 2
	$y1 = $b[0];	// 1
	$y2 = $b[1];	// 2

	return  ($a = karatsuba($x1, $y1)) * pow(10, 2 * $deg)
			+ ($c = karatsuba($x2, $y2))
			+ (karatsuba(sum($x1, $x2), sum($y1, $y2)) - $a - $c) * pow(10, $deg);
}

// 7 006 652
echo karatsuba($x, $y);
</pre>
<h2>Complexity</h2>
<p>Assuming that we replace two of the multiplications with only one makes the program faster. The question is how fast. Karatsuba improves the multiplication process by replacing the initial complexity of O(n<sup>2</sup>) by O(n<sup>lg3</sup>), which as you can see on the diagram below is much faster for big n.</p>
<figure id="attachment_3141" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/05/Karatsuba-Complexity.png"><img src="/wp-content/uploads/2012/05/Karatsuba-Complexity.png" alt="Karatsuba Complexity" title="Karatsuba Complexity" width="600" height="371" class="size-full wp-image-3141" srcset="/wp-content/uploads/2012/05/Karatsuba-Complexity.png 600w, /wp-content/uploads/2012/05/Karatsuba-Complexity-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">O(n^2) grows much faster than O(n^lg3)</figcaption></figure>
<h2>Application</h2>
<p>It&#8217;s obvious where the Karatsuba algorithm can be used. It is very efficient when it comes to integer multiplication, but that isn’t its only advantage. It is often used for polynomial multiplications.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2013/01/14/computer-algorithms-multiplication/" rel="bookmark" title="Computer Algorithms: Multiplication">Computer Algorithms: Multiplication </a></li>
<li><a href="/2012/11/26/computer-algorithms-strassens-matrix-multiplication/" rel="bookmark" title="Computer Algorithms: Strassen&#8217;s Matrix Multiplication">Computer Algorithms: Strassen&#8217;s Matrix Multiplication </a></li>
<li><a href="/2012/05/08/computer-algorithms-determine-if-a-number-is-prime/" rel="bookmark" title="Computer Algorithms: Determine if a Number is Prime">Computer Algorithms: Determine if a Number is Prime </a></li>
<li><a href="/2012/12/24/computer-algorithms-sorting-in-linear-time/" rel="bookmark" title="Computer Algorithms: Sorting in Linear Time">Computer Algorithms: Sorting in Linear Time </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/05/15/computer-algorithms-karatsuba-fast-multiplication/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>
