<?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>So Jake Says &#187; Primality Testing</title>
	<atom:link href="http://www.jakevoytko.com/blog/tag/primality-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jakevoytko.com/blog</link>
	<description>Ye Olde Computer Science Blogge</description>
	<lastBuildDate>Sun, 17 Jan 2010 15:16:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Number Theory for Programmers, Part 1</title>
		<link>http://www.jakevoytko.com/blog/2007/09/16/number-theory-for-programmers-part-1/</link>
		<comments>http://www.jakevoytko.com/blog/2007/09/16/number-theory-for-programmers-part-1/#comments</comments>
		<pubDate>Sun, 16 Sep 2007 20:19:19 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Fermat's Method]]></category>
		<category><![CDATA[Number Theory]]></category>
		<category><![CDATA[Primality Testing]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/2007/09/16/number-theory-for-programmers-part-1/</guid>
		<description><![CDATA[What is Number Theory? Number theory is the study of numbers, their properties, and what can be inferred from their properties. For programmers, it is most practical to focus on the theory of positive integers. Who should use this guide? Those who did not know the answer to the above question. How do we use [...]]]></description>
			<content:encoded><![CDATA[<h3>What is Number Theory?</h3>
<p>Number theory is the study of numbers, their properties, and what can be inferred from their properties. For programmers, it is most practical to focus on the theory of positive integers.</p>
<h3>Who should use this guide?</h3>
<p>Those who did not know the answer to the above question.</p>
<h3>How do we use modulus?</h3>
<p>First, we should bridge the gap between a Programmer&#8217;s definition of modulus and a Mathematician&#8217;s.</p>
<p><strong>Programmer</strong>: <em>a % b</em> is the remainder of <em>a / b</em>. Essentially, the programmer uses the following equation:</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/5c0bab0c3f7fbc8b463ff5d78236973c_1.83333pt.gif' title='a = b*c + r' alt='a = b*c + r'  style="vertical-align:-1.83333pt;" ></p>
<p>That is, the programmer says If we were finding 23 % 5, we would have:<br />
<img src='/blog/wp-content/plugins/latexrender/pictures/ef9bbd57cbb49f7fd02f8ae7e6b3ef03_1.83333pt.gif' title='23 = 5*4 + 3' alt='23 = 5*4 + 3'  style="vertical-align:-1.83333pt;" ><br />
<img src='/blog/wp-content/plugins/latexrender/pictures/37693cfc748049e45d87b8c7d8b9aacd_1.0pt.gif' title='23' alt='23'  style="vertical-align:-1.0pt;" > % <img src='/blog/wp-content/plugins/latexrender/pictures/4c31ffa20fa4cbd5d1cea980f758157e_1.0pt.gif' title='5 = 3' alt='5 = 3'  style="vertical-align:-1.0pt;" >.</p>
<p><strong>Mathematician</strong>: Mathematicians rearrange the above equation into the following:</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/a8abb65be73f763a005feeaa5ce2189d.gif' title='a &amp;#8211; r = bc' alt='a &amp;#8211; r = bc'  align=absmiddle>. They write this as:</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/77b99e9bc51689a475314f0937b4128a_3.5pt.gif' title='a \equiv r ($mod$\  b)' alt='a \equiv r ($mod$\  b)'  style="vertical-align:-3.5pt;" ></p>
<p>All this means is that you can move from <em>a </em>to <em>r</em> just by adding and subtracting <em>b</em>.<br />
23 &#8211; 5 &#8211; 5 &#8211; 5 &#8211; 5 = 3, so <img src='/blog/wp-content/plugins/latexrender/pictures/e7aedcd748c0f4ae851ea5f6827deb17_3.5pt.gif' title='23 \equiv 3 (mod\ 5)' alt='23 \equiv 3 (mod\ 5)'  style="vertical-align:-3.5pt;" ></p>
<h3>Efficient Exponentiation (mod <em>n</em>)</h3>
<p>Let&#8217;s say that you need to find <img src='/blog/wp-content/plugins/latexrender/pictures/014b154b2ba42fb9e1c80d1b02804839_3.5pt.gif' title='a ^{x} (mod\ n)' alt='a ^{x} (mod\ n)'  style="vertical-align:-3.5pt;" >. The naive way of doing this is to perform the operation just as it&#8217;s written:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> powmod<span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> a<span style="color: #339933;">,</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> x<span style="color: #339933;">,</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> n<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> pow<span style="color: #009900;">&#40;</span>a<span style="color: #339933;">,</span> x<span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> n<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>and it has a few disadvantages.</p>
<ol>
<li>It has a very good chance of overflowing native data types</li>
<li>It has an algorithmic complexity of O(<em>n</em>) for the size of the exponent. For large integer types, this becomes O(<em>nm</em>), for integers of (on average) <em>m</em>words</li>
</ol>
<p>To show a more efficient way of doing it, we will use a method called &#8220;successive squaring&#8221;. I will explain it by using an example: Find <img src='/blog/wp-content/plugins/latexrender/pictures/7799c43c67f34958b77d6a3ab07cb9cd_3.5pt.gif' title='3 ^ {17} (mod\ 5)' alt='3 ^ {17} (mod\ 5)'  style="vertical-align:-3.5pt;" >:</p>
<p>We know that <img src='/blog/wp-content/plugins/latexrender/pictures/591e0b302dcbce1b6385784731609932_3.5pt.gif' title='3 ^ {17} (mod\ 5) \equiv 3^{16} * 3^{1} (mod\ 5)' alt='3 ^ {17} (mod\ 5) \equiv 3^{16} * 3^{1} (mod\ 5)'  style="vertical-align:-3.5pt;" >. We need to find <img src='/blog/wp-content/plugins/latexrender/pictures/d6ec409f0a2cdff55a22279c47a62839_3.5pt.gif' title='3^{16}(mod\ 5)' alt='3^{16}(mod\ 5)'  style="vertical-align:-3.5pt;" >:</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/f14c04e5d758ab7d82fc6d382212a202_3.5pt.gif' title='3 \equiv 3 (mod\ 5)' alt='3 \equiv 3 (mod\ 5)'  style="vertical-align:-3.5pt;" >. This is given.</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/662626b01c91a3c6caf8f96bbc845c6a_3.5pt.gif' title='3^{2} \equiv 9 \equiv 4 (mod\ 5)' alt='3^{2} \equiv 9 \equiv 4 (mod\ 5)'  style="vertical-align:-3.5pt;" ></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/2677fb23d7eff3992f854c22b41a4e3a_3.5pt.gif' title='3^{4} \equiv (3^{2})^{2} \equiv 4^{2} \equiv 16 \equiv 1 (mod\ 5)' alt='3^{4} \equiv (3^{2})^{2} \equiv 4^{2} \equiv 16 \equiv 1 (mod\ 5)'  style="vertical-align:-3.5pt;" >.</p>
<p>This is where the leap of logic occurs. Since <img src='/blog/wp-content/plugins/latexrender/pictures/1ecc2e4b54b1677c15c57efaf3478cdf_3.5pt.gif' title='3^{2} \equiv 4 (mod\ 5)' alt='3^{2} \equiv 4 (mod\ 5)'  style="vertical-align:-3.5pt;" >, it follows that <img src='/blog/wp-content/plugins/latexrender/pictures/f047db04c4e0aee3a1af6e4054225db2_3.5pt.gif' title='3^{4} \equiv (3^{2})^{2}' alt='3^{4} \equiv (3^{2})^{2}'  style="vertical-align:-3.5pt;" ></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/463eadc74dbf9aad216b55449c95e656_3.5pt.gif' title='3^{8} \equiv 1 (mod\ 5)' alt='3^{8} \equiv 1 (mod\ 5)'  style="vertical-align:-3.5pt;" ></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/de98530786b1586bd9f2c4b8084b8bc0_3.5pt.gif' title='3^{16} \equiv 1 (mod\ 5)' alt='3^{16} \equiv 1 (mod\ 5)'  style="vertical-align:-3.5pt;" ></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/d7434bcad4ce2e8d6b23330250ed4297_3.5pt.gif' title='3^{17} = 3^{16} * 3^{1} = 1 * 3 \equiv 3 (mod\ 5)' alt='3^{17} = 3^{16} * 3^{1} = 1 * 3 \equiv 3 (mod\ 5)'  style="vertical-align:-3.5pt;" ></p>
<p>So <img src='/blog/wp-content/plugins/latexrender/pictures/f281266801a868c3ea6bb494f86bf350_1.0pt.gif' title='3^{17}' alt='3^{17}'  style="vertical-align:-1.0pt;" > % 5 = 3, and I was able to do it all in my head! For small numbers, this is usually the case. But it should be obvious that this is a lot easier than ordinary exponentiation, with on the order of O(log<em>n</em>) multiplications.</p>
<p><strong>Code example</strong></p>
<p>The best code example I have found is from Bruce Schneier&#8217;s &#8220;Applied Cryptography&#8221;. The C version using native unsigned integers is as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> powmod<span style="color: #009900;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> base<span style="color: #339933;">,</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> exp<span style="color: #339933;">,</span> <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> mod<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> toret<span style="color: #339933;">=</span><span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span>exp <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>exp <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span>
            toret <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>toret <span style="color: #339933;">*</span> base<span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> mod<span style="color: #339933;">;</span>
&nbsp;
        exp <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;&amp;</span>gt<span style="color: #339933;">;=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
        base<span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span>base<span style="color: #339933;">*</span>base<span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> mod<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">return</span> toret<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>It&#8217;ll still overflow for the wrong values, but it is a quick and dirty example. If you have access to an infinite precision integer, it should be trivial to convert it.</p>
<h3>Fermat&#8217;s Little Theorem</h3>
<p>One of the many things that Fermat conjectured (and supposedly proved) is quite useful to the modern programmer. It says, for any prime number <em>p</em>, and for any integer <em>a</em></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/bda5a769e75fe05fb287502fa9558be7_3.5pt.gif' title='a^{p} \equiv a (mod\ p)' alt='a^{p} \equiv a (mod\ p)'  style="vertical-align:-3.5pt;" >.</p>
<p>Combined with the successive squaring method, this provides us a very powerful tool.</p>
<h3>Probabilistic Primality Testing</h3>
<p>For any number of applications, we need prime numbers. They are the crack-cocaine of modern mathematics. There are many simple ways to get prime numbers, such as the Sieve of Eratosthenes, but these methods fail when your application needs a 20-digit prime. There are newly developed (but complicated) tests that give a definite yes/no on a number in polynomial time, but they require Abstract Algebra, which is beyond the scope of this entry! For most developers, we don&#8217;t need to be 100% sure the numbers we are using are prime. We&#8217;re not using RSA in life-or-death (or multi-billion dollar banking) situations! All we want to do is tell whether or not an integer is most likely prime so that we can encrypt our <em>Dawson&#8217;s Creek</em> fan fiction and hide it from our father.</p>
<p>Fermat&#8217;s Little Theorem is always true if we know that the modulus is prime. The proof, however, doesn&#8217;t hold true in the opposite direction: if, for some number <em>a</em>, <img src='/blog/wp-content/plugins/latexrender/pictures/9ac82e8fab98ceb651fe26b7c6ccf38b_3.5pt.gif' title='a^{n} \equiv a (mod\ n)' alt='a^{n} \equiv a (mod\ n)'  style="vertical-align:-3.5pt;" >, we can&#8217;t say for sure that <em>n</em> is a prime. However, it is very frequently true, and often enough that we can form a probabilistic test, meaning that the numbers are probably prime. Mathematicians are noted for devastating understatement, so when we say &#8220;probably&#8221;, we mean &#8220;the chance is absurdly close to 100%&#8221;. According to <a href="http://www.it.pgp.net/pgp-faq/faq-appendix2.html#2.3">pgp.net</a>, PGP uses trial division for primes less than 8191, and the Fermat test for 2,3,5, and 7. I can&#8217;t find a reliable source covering the mathematics of why, but an <a href="http://en.wikipedia.org/wiki/Fermat_primality_test">unreliable source</a> gives the chance that a composite is picked as less than 1 in <img src='/blog/wp-content/plugins/latexrender/pictures/67d474f8b10467f44715eca2c9ac5770_1.0pt.gif' title='10^{50}' alt='10^{50}'  style="vertical-align:-1.0pt;" >. Yikes!</p>
<p><strong>The Test</strong></p>
<p>Ready?</p>
<p>For some number <em>n</em>, it is probably prime if:</p>
<ol>
<li><img src='/blog/wp-content/plugins/latexrender/pictures/126cef28aa6e7c5dd284390a1d12af3e_3.5pt.gif' title='2^{n} \equiv 2 (mod\ n)' alt='2^{n} \equiv 2 (mod\ n)'  style="vertical-align:-3.5pt;" ></li>
<li><img src='/blog/wp-content/plugins/latexrender/pictures/f7d8dd0dd38aa6f49de7b3f30580c593_3.5pt.gif' title='3^{n} \equiv 3 (mod\ n)' alt='3^{n} \equiv 3 (mod\ n)'  style="vertical-align:-3.5pt;" ></li>
</ol>
<p>If this makes you uncomfortable by using the first two primes, you can randomly pick two numbers (instead of 2 and 3). The test works just the same. For the ultra paranoid, try it three or four times.</p>
<p><strong>The Carmichael Numbers</strong></p>
<p>There are numbers that cause this test to fail for all test values. They are called <a href="http://mathworld.wolfram.com/CarmichaelNumber.html">Carmichael numbers</a>, named after the first person to find an example. The first three are 561, 1105, and 1729. There are infinitely many Carmichael numbers, though they grow more scarce as the integers approach infinity. For fun, use the method of successive squaring to show that 561 is a Carmichael number.</p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=12&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2007/09/16/number-theory-for-programmers-part-1/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>
