<?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; Number Theory</title>
	<atom:link href="http://www.jakevoytko.com/blog/tag/number-theory/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</generator>
		<item>
		<title>Why Does RSA Work?</title>
		<link>http://www.jakevoytko.com/blog/2008/01/06/why-does-rsa-work/</link>
		<comments>http://www.jakevoytko.com/blog/2008/01/06/why-does-rsa-work/#comments</comments>
		<pubDate>Mon, 07 Jan 2008 02:05:54 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Decryption]]></category>
		<category><![CDATA[Encryption]]></category>
		<category><![CDATA[Number Theory]]></category>
		<category><![CDATA[RSA]]></category>
		<category><![CDATA[Schneier]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/2008/01/06/why-does-rsa-work/</guid>
		<description><![CDATA[To skip to the math, scroll down or click here. The Algorithm The algorithm is divided into three stages: precalculation, encryption, and decryption. Precalculation is performed a single time for each person with a public/private key pair, and encryption/decryption is performed for each message. Precalculation Pick primes: Find two arbitrarily large prime numbers, p and [...]]]></description>
			<content:encoded><![CDATA[<p><em>To skip to the math, scroll down or <a href="#rsa_math">click here.</a></em></p>
<p><img src="http://www.jakevoytko.com/blog/wp-content/uploads/2008/01/adleman_r_s.jpg" alt="adleman_r_s.jpg" /></p>
<h2>The Algorithm</h2>
<p>The algorithm is divided into three stages: precalculation, encryption, and decryption. Precalculation is performed a single time for each person with a public/private key pair, and encryption/decryption is performed for each message.</p>
<p><strong>Precalculation</strong></p>
<ol>
<li><span style="text-decoration: underline;">Pick primes</span><em>: </em>Find two arbitrarily large prime numbers, <em>p</em> and <em>q</em>.</li>
</ol>
<ol>
<li><span style="text-decoration: underline;">Determine the modulus</span>: Multiply <em>p </em>and <em>q</em> to get <em>n</em>. This will be your modulus for all equations.</li>
</ol>
<ol>
<li><span style="text-decoration: underline;">Calculate phi(n)</span>: Using Euler&#8217;s <a href="#totient">totient function</a>, calculate <img src='/blog/wp-content/plugins/latexrender/pictures/8c3daefe5bb907b8ba6db6b68be61371_3.5pt.gif' title='$\phi(n) = (p-1) * (q-1)$' alt='$\phi(n) = (p-1) * (q-1)$'  style="vertical-align:-3.5pt;" > . This number is a secret number, so don&#8217;t give it away. The strength of the algorithm depends on <img src='/blog/wp-content/plugins/latexrender/pictures/f4bdf2149704f6b9d6d0068d05021138_3.5pt.gif' title='$\phi(n)$' alt='$\phi(n)$'  style="vertical-align:-3.5pt;" > being hard to calculate when given a sufficiently large <em>n = p * q</em></li>
</ol>
<ol>
<li><span style="text-decoration: underline;">Determine an encryption exponent</span>: Take any number, <em>e</em>, such that GCD(<img src='/blog/wp-content/plugins/latexrender/pictures/f4bdf2149704f6b9d6d0068d05021138_3.5pt.gif' title='$\phi(n)$' alt='$\phi(n)$'  style="vertical-align:-3.5pt;" >, <em>e</em>) = 1. This means that they are <em><a href="http://www.jakevoytko.com/blog/2007/09/23/number-theory-for-programmers-part-2/">relatively prime</a></em>, and share no common factors. This number is considered your public key (when combined with <em>n</em>), and you can give this number to whoever you like.</li>
</ol>
<ol>
<li><span style="text-decoration: underline;">Compute the decryption exponent</span><em>:</em> Solve the <em><a href="#euclidean">Extended Euclidean Algorithm</a></em> of GCD(<img src='/blog/wp-content/plugins/latexrender/pictures/f4bdf2149704f6b9d6d0068d05021138_3.5pt.gif' title='$\phi(n)$' alt='$\phi(n)$'  style="vertical-align:-3.5pt;" >, e) to find <img src='/blog/wp-content/plugins/latexrender/pictures/506ad5480ebbbba8fc18288a504b6748_1.0pt.gif' title='e^{-1}' alt='e^{-1}'  style="vertical-align:-1.0pt;" >. This is your private key.</li>
</ol>
<p>We have a private decryption key pair: <em>{n, d}, </em>and a public encryption key pair: <em>{n, e}</em>.</p>
<p><strong>Encryption</strong></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/1aa9538eb07872740d6b24fb4b8d4f11_3.5pt.gif' title='$m_{1} \equiv m^{e} (mod\ n)$' alt='$m_{1} \equiv m^{e} (mod\ n)$'  style="vertical-align:-3.5pt;" ></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/96def595395241fe3de787a7597a9021_2.49998pt.gif' title='$m_{1}$' alt='$m_{1}$'  style="vertical-align:-2.49998pt;" > is the encrypted message, and it can safely be sent publicly.</p>
<p><strong>Decryption</strong></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/ca9c8e2a8355ae89777001437050f3f6_3.5pt.gif' title='$m_{2} \equiv m_{1}^d (mod\ n)$' alt='$m_{2} \equiv m_{1}^d (mod\ n)$'  style="vertical-align:-3.5pt;" ></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/8e3acbbfc26099340474ce98c66b8490_2.49998pt.gif' title='$m_{2}$' alt='$m_{2}$'  style="vertical-align:-2.49998pt;" > is the decrypted message. The person with the private key for the message will be able to read it, and theoretically, nobody else.</p>
<p><strong>Is the message preserved?</strong></p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/d867bc3f64c350ae7b5df118025ff437_3.5pt.gif' title='$m_{2} \equiv m_{1}^{d} (mod\ n) \equiv m^{ed} (mod\ n)' alt='$m_{2} \equiv m_{1}^{d} (mod\ n) \equiv m^{ed} (mod\ n)'  style="vertical-align:-3.5pt;" ></p>
<p>Applying the <em><a href="#euler_corollary">Corollary to Euler&#8217;s Theorem</a></em> to <img src='/blog/wp-content/plugins/latexrender/pictures/62139464e5724a75e09b2061874a68fc_3.5pt.gif' title='$m^{ed} (mod\ n)$' alt='$m^{ed} (mod\ n)$'  style="vertical-align:-3.5pt;" >, we get <img src='/blog/wp-content/plugins/latexrender/pictures/aa358c65fd3c4dca33ffbc8896a7510d_3.5pt.gif' title='$m^{1} (mod\ n) \equiv m$' alt='$m^{1} (mod\ n) \equiv m$'  style="vertical-align:-3.5pt;" >.</p>
<p>We also notice that <img src='/blog/wp-content/plugins/latexrender/pictures/b44b387c2fae8bb389fbef405fc6b930_3.5pt.gif' title='$m^{ed} \equiv m^{ee^{-1}} \equiv m (mod\ n)$' alt='$m^{ed} \equiv m^{ee^{-1}} \equiv m (mod\ n)$'  style="vertical-align:-3.5pt;" ></p>
<p><strong>Why is it hard for an attacker to crack?</strong></p>
<p>In a perfect world, the attacker needs to solve some equivalent of the <em><a href="http://en.wikipedia.org/wiki/Integer_factorization">Integer Factorization Problem</a></em> to factor <em>n</em>, which is suspected to be outside of complexity class P using classical computation. If we have access to quantum computers, we have access to an algorithm, <a href="http://en.wikipedia.org/wiki/Shor's_algorithm">Shor&#8217;s Algorithm</a>, to crack integer factorization efficiently, but probabilistically.</p>
<p>The essential problem that the attacker faces is as follows: they have the encryption exponent and the modulus. They know what <em>n</em> is, but they currently have no method of calculating what <img src='/blog/wp-content/plugins/latexrender/pictures/f4bdf2149704f6b9d6d0068d05021138_3.5pt.gif' title='$\phi(n)$' alt='$\phi(n)$'  style="vertical-align:-3.5pt;" > is without first factoring <em>n</em>. They need to find the decryption exponent, <em>d = <img src='/blog/wp-content/plugins/latexrender/pictures/947268967467ff4aa2ebe810f8c7b60f_1.0pt.gif' title='$e^{-1}$' alt='$e^{-1}$'  style="vertical-align:-1.0pt;" >,</em>, but can&#8217;t find the exponent without being able to solve the <em>Extended Euclidean Algorithm</em>, where they need to know the value of <img src='/blog/wp-content/plugins/latexrender/pictures/f4bdf2149704f6b9d6d0068d05021138_3.5pt.gif' title='$\phi(n)$' alt='$\phi(n)$'  style="vertical-align:-3.5pt;" >. So long as <em>n</em> is hard to factor, RSA will remain difficult to break.</p>
<p>We don&#8217;t live in a perfect world, and there are plenty of examples of attacks that take advantage of weak implementations of RSA. See <a href="http://tools.ietf.org/html/rfc3447#page-6">RFC 3447</a> for some best practices.</p>
<h2>The Math</h2>
<p><a name="rsa_math"></a><br />
<strong><a name="euclidean"></a>Extended Euclidean Algorithm</strong></p>
<p>The <em>Euclidean Algorithm</em> finds the Greatest Common Divisor (GCD) of two integers, <em>a</em> and <em>b.</em> The <em>Extended Euclidean Algorithm</em> finds integers <em>m</em> and <em>n</em> in the following equation:</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/e75dfd8e4bfee86535502787f332ac0d_3.5pt.gif' title='$GCD(a,\ b) = m * a + n * b' alt='$GCD(a,\ b) = m * a + n * b'  style="vertical-align:-3.5pt;" ></p>
<p><span style="text-decoration: underline;">Euclidean Algorithm</span></p>
<p>To see how it does this, we will look at an example. Let <em>a</em> = 200, <em>b</em> = 37. Please note that 200 = <img src='/blog/wp-content/plugins/latexrender/pictures/1ed346930917426bc46d41e22cc525ec_2.94444pt.gif' title='\phi' alt='\phi'  style="vertical-align:-2.94444pt;" >(101 * 3). Since (200, 37) = 1, this is the equivalent of trying to find 37-1 (mod 200). For previous writings on the material, click here.</p>
<blockquote>
<ol>
<li><img src='/blog/wp-content/plugins/latexrender/pictures/f364ad298499010b6c41859eb464a297_1.83333pt.gif' title='$200 = 37 * 5 + 15$' alt='$200 = 37 * 5 + 15$'  style="vertical-align:-1.83333pt;" ></li>
<li><img src='/blog/wp-content/plugins/latexrender/pictures/5e4e4077ef4f088cbd9dc5aeb14f0728_1.83333pt.gif' title='$37 = 15 * 2 + 7$' alt='$37 = 15 * 2 + 7$'  style="vertical-align:-1.83333pt;" ></li>
<li><img src='/blog/wp-content/plugins/latexrender/pictures/98683372abe86293f38b37105d32c221_1.83333pt.gif' title='$15 = 7 * 2 + 1$' alt='$15 = 7 * 2 + 1$'  style="vertical-align:-1.83333pt;" ></li>
<li><img src='/blog/wp-content/plugins/latexrender/pictures/c6c639e36962dc17e3ae1299e298462c_1.83333pt.gif' title='$7 = 1 * 7 + 0$' alt='$7 = 1 * 7 + 0$'  style="vertical-align:-1.83333pt;" ></li>
</ol>
<p>Line 3 is considered the &#8220;final&#8221; line of the algorithm because it is the last line where the remainder is nonzero. The remainder of that line, 1, is also GCD(200, 37).</p></blockquote>
<p><span style="text-decoration: underline;">Extended Euclidean Algorithm</span></p>
<blockquote><p>We start by rewriting every equation so that the remainder is on the RHS.</p>
<ol>
<li><img src='/blog/wp-content/plugins/latexrender/pictures/6f1119aaa4676402b94a91b8c419a7d7.gif' title='$15 = 200 &amp;#8211; 5 * 37$' alt='$15 = 200 &amp;#8211; 5 * 37$'  align=absmiddle></li>
<li><img src='/blog/wp-content/plugins/latexrender/pictures/a2116d8125db7b822e12a7061da88670.gif' title='$7 = 37 &amp;#8211; 2 * 15$' alt='$7 = 37 &amp;#8211; 2 * 15$'  align=absmiddle></li>
<li><img src='/blog/wp-content/plugins/latexrender/pictures/b8b9d4527b1cfbe334daa095ecc21765.gif' title='$1 = 15 &amp;#8211; 2 * 7$' alt='$1 = 15 &amp;#8211; 2 * 7$'  align=absmiddle></li>
</ol>
<p>From here, we start at line 3, and substitute in line 2. Don&#8217;t simplify any multiplications, just the additions.</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/56ae81fde4832cce6d1c14b9afdebafb.gif' title='$1 = 15 &amp;#8211; 2 * 7 = 15 &amp;#8211; 2 * (37 &amp;#8211; 2 * 15)$' alt='$1 = 15 &amp;#8211; 2 * 7 = 15 &amp;#8211; 2 * (37 &amp;#8211; 2 * 15)$'  align=absmiddle><br />
<img src='/blog/wp-content/plugins/latexrender/pictures/4f2911dc78845705774c34854ac36620.gif' title='$1 = 5 * 15 &amp;#8211; 2 * 37$' alt='$1 = 5 * 15 &amp;#8211; 2 * 37$'  align=absmiddle></p>
<p>Substitute line 1 into the resulting equation.</p>
<p>[Unparseable or potentially dangerous latex formula. Error 5 : 533x369]</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/95a8e87ded93c7161168f4963dce3c7d.gif' title='$1 = 5 * 200 &amp;#8211; 27 * 37$' alt='$1 = 5 * 200 &amp;#8211; 27 * 37$'  align=absmiddle></p></blockquote>
<p>We now have everything that we need for the inverse of 37. It turns out that <img src='/blog/wp-content/plugins/latexrender/pictures/95a8e87ded93c7161168f4963dce3c7d.gif' title='$1 = 5 * 200 &amp;#8211; 27 * 37$' alt='$1 = 5 * 200 &amp;#8211; 27 * 37$'  align=absmiddle> is equivalent to saying:</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/f0a630494ed21992307526d3803cd79a_3.5pt.gif' title='$-27 * 37 \equiv 173 * 37 \equiv 1 (mod\ 200)' alt='$-27 * 37 \equiv 173 * 37 \equiv 1 (mod\ 200)'  style="vertical-align:-3.5pt;" ></p>
<p>so 173 is the multiplicative inverse of 37 (mod 200). Neat, huh?</p>
<p><strong><a name="Fermat"></a>Fermat&#8217;s Little Theorem + Euler&#8217;s Theorem</strong></p>
<p><img src="http://www.jakevoytko.com/blog/wp-content/uploads/2008/01/pierre_de_fermat.png" alt="pierre_de_fermat.png" /><br />
In a letter written in 1640, Fermat (of Pythagorean fame) offhandedly mentioned that he had noticed and proved the following relation:</p>
<p><span style="text-decoration: underline;">Fermat&#8217;s Little Theorem</span></p>
<blockquote><p>For <em>a</em> any integer, and <em>p</em> prime,</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/eed0a89e26b8b8947f6dff7d05933039_3.5pt.gif' title='$a^{p-1} \equiv 1 (mod\ p)$' alt='$a^{p-1} \equiv 1 (mod\ p)$'  style="vertical-align:-3.5pt;" ></p></blockquote>
<p>As he is <a href="http://en.wikipedia.org/wiki/Fermat's_last_theorem">occasionally noted for doing</a>, he did not bother to write down the proof. Leibniz is said to have proved it, but didn&#8217;t get around to publishing it. He was an inventor of calculus, so we&#8217;ll cut him some slack.</p>
<p><img src="http://www.jakevoytko.com/blog/wp-content/uploads/2008/01/leonhard_euler.jpg" alt="leonhard_euler.jpg" /></p>
<p>Enter Leonhard Euler. Euler was 18 feet tall, shot laser beams from his eyes, and <a href="http://en.wikipedia.org/wiki/List_of_topics_named_after_Leonhard_Euler">proved Mathematics every second he was awake</a>. In 1736, he took 23 minutes off from a conquest of Mars to prove Fermat&#8217;s Little Theorem.</p>
<p>This wasn&#8217;t enough, though. He attempted to find a way to generalize it for any number, <em>n</em>, instead of just for primes, <em>p</em>, but couldn&#8217;t.  The problem tortured him for 24 years, when in 1760* he was finally able to produce his <a href="http://www.cut-the-knot.org/blue/Euler.shtml">proof</a>.</p>
<p>His proof makes use of a function he defines, phi(x).</p>
<p><a name="totient"></a><span style="text-decoration: underline;">Euler&#8217;s Totient Function</span></p>
<blockquote><p>For any positive integer, <em>n</em>, <img src='/blog/wp-content/plugins/latexrender/pictures/f4bdf2149704f6b9d6d0068d05021138_3.5pt.gif' title='$\phi(n)$' alt='$\phi(n)$'  style="vertical-align:-3.5pt;" > is equal to the number of positive integers where GCD(<em>a, n</em>) = 1, for <em>a</em> &lt; <em>n</em>.</p>
<p>Most germane to this discussion, for any prime, <em>p</em>, <img src='/blog/wp-content/plugins/latexrender/pictures/1440b24e3db52e2fcb1b6cd9f6cb4035_3.5pt.gif' title='$\phi(n)$ = p-1' alt='$\phi(n)$ = p-1'  style="vertical-align:-3.5pt;" >. This makes perfect sense, of course, as a prime is indivisible, and therefore all numbers less than <em>p</em> don&#8217;t share factors with <em>p</em>, or else <em>p</em> could be divided!</p></blockquote>
<p>The formula ends up being:</p>
<p><span style="text-decoration: underline;">Euler&#8217;s Theorem</span></p>
<blockquote><p>For any positive integers <em>a, n</em>:</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/7c39c47c1950b82a4fb0723bd97f801d_3.5pt.gif' title='$a^{\phi(n)} \equiv 1 (mod\ n)$' alt='$a^{\phi(n)} \equiv 1 (mod\ n)$'  style="vertical-align:-3.5pt;" ></p></blockquote>
<p>* Wikipedia says 1736, <a href="http://www.amazon.com/gp/redirect.html?ie=UTF8&amp;location=http%3A%2F%2Fwww.amazon.com%2FElementary-Number-Theory-Kenneth-Rosen%2Fdp%2F0321237072%3Fie%3DUTF8%26s%3Dbooks%26qid%3D1199671115%26sr%3D8-2&amp;tag=jakvoyshom-20&amp;linkCode=ur2&amp;camp=1789&amp;creative=9325">my number theory book</a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=jakvoyshom-20&amp;l=ur2&amp;o=1" border="0" alt="" width="1" height="1" /> says 1760, tie goes to the book.</p>
<p><strong><a name="euler_corollary"></a>Corollary to Euler&#8217;s Theorem</strong></p>
<p>Because <img src='/blog/wp-content/plugins/latexrender/pictures/7c39c47c1950b82a4fb0723bd97f801d_3.5pt.gif' title='$a^{\phi(n)} \equiv 1 (mod\ n)$' alt='$a^{\phi(n)} \equiv 1 (mod\ n)$'  style="vertical-align:-3.5pt;" >, we can reduce the multiplication needed for any power of <em>a</em> &gt; <em>n</em>.</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/ff8bed3e1d7d25a9f3ff424b32df92d4_3.5pt.gif' title='$a^{b} \equiv a^{b (mod\ \phi(n))} (mod\ n)$' alt='$a^{b} \equiv a^{b (mod\ \phi(n))} (mod\ n)$'  style="vertical-align:-3.5pt;" ></p>
<p><em>Edit: added link to Wikipedia&#8217;s article on Integer Factorization, and a better explanation of why the attack is hard</em></p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=31&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2008/01/06/why-does-rsa-work/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Number Theory, Hash Tables, and Geometric Progressions</title>
		<link>http://www.jakevoytko.com/blog/2007/09/30/number-theory-hash-tables-and-geometric-progressions/</link>
		<comments>http://www.jakevoytko.com/blog/2007/09/30/number-theory-hash-tables-and-geometric-progressions/#comments</comments>
		<pubDate>Sun, 30 Sep 2007 17:48:13 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Geometric Sequence]]></category>
		<category><![CDATA[Hash table]]></category>
		<category><![CDATA[Number Theory]]></category>
		<category><![CDATA[Phi]]></category>
		<category><![CDATA[Primitive Root]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/2007/09/30/number-theory-hash-tables-and-geometric-progressions/</guid>
		<description><![CDATA[Or, and Loathing in Los Vegas What will this article focus on? This particular article looks at geometric sequences (mod n), and how we can use them instead of linear hashes. A geometric sequence is simply a sequence of powers of some number: 1, , , , &#8230; So instead of adding the same number [...]]]></description>
			<content:encoded><![CDATA[<p>Or, <strong><img src='/blog/wp-content/plugins/latexrender/pictures/1ed346930917426bc46d41e22cc525ec_2.94444pt.gif' title='\phi' alt='\phi'  style="vertical-align:-2.94444pt;" > and Loathing in Los Vegas</strong></p>
<h3>What will this article focus on?</h3>
<p>This particular article looks at geometric sequences (mod <em>n</em>), and how we can use them instead of linear hashes. A <strong>geometric sequence</strong> is simply a sequence of powers of some number: 1, <img src='/blog/wp-content/plugins/latexrender/pictures/0cc175b9c0f1b6a831c399e269772661_1.0pt.gif' title='a' alt='a'  style="vertical-align:-1.0pt;" >, <img src='/blog/wp-content/plugins/latexrender/pictures/ebc3d7bedc1f11e08895c3124001cbb5_1.0pt.gif' title='a^2' alt='a^2'  style="vertical-align:-1.0pt;" >, <img src='/blog/wp-content/plugins/latexrender/pictures/0e12d972c205ea4de06749a887ff1ffe_1.0pt.gif' title='a^3' alt='a^3'  style="vertical-align:-1.0pt;" >, &#8230; So instead of adding the same number together a bunch of times, we&#8217;re multiplying it together a bunch of times. And then you subtract one. More on that below!</p>
<h3>First, the math</h3>
<p><strong>Euler&#8217;s Phi Function</strong></p>
<p>When Euler was attempting to generalize <a href="http://www.jakevoytko.com/blog/2007/09/16/number-theory-for-programmers-part-1/">Fermat&#8217;s Little Theorem</a>, he defined a function using the Greek symbol <img src='/blog/wp-content/plugins/latexrender/pictures/1ed346930917426bc46d41e22cc525ec_2.94444pt.gif' title='\phi' alt='\phi'  style="vertical-align:-2.94444pt;" > (pronounced fee by most people I&#8217;ve encountered). It has a simple job: it takes in a natural number, <em>n</em>, and returns the number of positive integers less than <em>n</em> that are <a href="http://www.jakevoytko.com/blog/2007/09/23/number-theory-for-programmers-part-2/">relatively prime </a>to <em>n</em>. In this article, we are not concerned with <img src='/blog/wp-content/plugins/latexrender/pictures/1ed346930917426bc46d41e22cc525ec_2.94444pt.gif' title='\phi' alt='\phi'  style="vertical-align:-2.94444pt;" >&#8216;s calculation for anything but prime numbers.</p>
<p>It is easy to show that <img src='/blog/wp-content/plugins/latexrender/pictures/1ed346930917426bc46d41e22cc525ec_2.94444pt.gif' title='\phi' alt='\phi'  style="vertical-align:-2.94444pt;" >(p) = p-1 when p is prime: all numbers less than a prime are relatively prime to the prime in question, otherwise it wouldn&#8217;t be prime! Easy proof.</p>
<p>Euler&#8217;s phi function is of vital to the RSA encryption algorithm, and is the cornerstone of the generalization of Fermat&#8217;s Little Theorem, but it makes cameo appearances in many other areas of mathematics.</p>
<p>Examples:</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/1ed346930917426bc46d41e22cc525ec_2.94444pt.gif' title='\phi' alt='\phi'  style="vertical-align:-2.94444pt;" >(5) = 4, because gcd(5, 1) = gcd(5, 2) = gcd(5, 3), = gcd(5, 4) = 1.</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/1ed346930917426bc46d41e22cc525ec_2.94444pt.gif' title='\phi' alt='\phi'  style="vertical-align:-2.94444pt;" >(6) = 2, because gcd(6, 1) = gcd(6, 5) = 1, but gcd(6, 2) = 2, gcd(6, 3) = 3, and gcd(6, 4) = 2.</p>
<p><strong>Order of a number (mod n)</strong></p>
<p>The <strong>order</strong> of a number (mod n), where n is an integer, is the smallest positive value of <em>x</em> such that <img src='/blog/wp-content/plugins/latexrender/pictures/6043e99443887a278ea012378e2faf9a_3.5pt.gif' title='s^x \equiv 1(mod\ p)' alt='s^x \equiv 1(mod\ p)'  style="vertical-align:-3.5pt;" >. If it is never equal to 1, it is considered infinite. 6 (mod 10) is an example that never has an answer. Note that this still has a solution under Euler&#8217;s generalization of Fermat&#8217;s Little Theorem. The laws of the universe won&#8217;t let you off that easy.</p>
<p><strong>Example</strong>:</p>
<p>The order of 2 (mod 7) is 3, because [Unparseable or potentially dangerous latex formula. Error 1 ](prime) = prime-1, so <img src='/blog/wp-content/plugins/latexrender/pictures/1ed346930917426bc46d41e22cc525ec_2.94444pt.gif' title='\phi' alt='\phi'  style="vertical-align:-2.94444pt;" >(p) = p-1. If order(m) (mod p) is p-1, that means that m is a generator for all numbers (mod p) except p itself! Since this will not generate p, and 0 by extension, (since they are in the same congruence class), we must subtract our result by 1. So our generator is <em>m</em>, and our hash function is <img src='/blog/wp-content/plugins/latexrender/pictures/a37ed226c9e6b3696ff43f2451cd1c40.gif' title='a^x &amp;#8211; 1(mod\ prime)' alt='a^x &amp;#8211; 1(mod\ prime)'  align=absmiddle></p>
<p>It is not true that all numbers have a primitive root, but it WAS proved by Legendre that every prime has at least one generator (mod p). Interestingly, according to my college Number Theory textbook, Euler tried his hand at the proof, but was incorrect. To the uninitiated into the <em>Cult of Euler,</em> this would be akin to a team of Michael Jordan clones failing to score a single point in a basketball game against a team of middle school students.</p>
<p>We need to find one such that the first time this happens is for a power of p-1. Instead of testing every power, we can instead (because of this proof), just test powers where the power divides p-1. If we were looking mod 9, and we knew 3^8 == 1(mod p) (which it has to be because of Fermat&#8217;s Little Theorem), then <img src='/blog/wp-content/plugins/latexrender/pictures/d7b213cee95b4b6b3ab6b90cadfed175_1.0pt.gif' title='3^1' alt='3^1'  style="vertical-align:-1.0pt;" >, <img src='/blog/wp-content/plugins/latexrender/pictures/15a774bb3441106ae6145acd8b634821_1.0pt.gif' title='3^2' alt='3^2'  style="vertical-align:-1.0pt;" >, <img src='/blog/wp-content/plugins/latexrender/pictures/a0faf7b4c911b1fd4448c87db5067057_1.0pt.gif' title='3^4' alt='3^4'  style="vertical-align:-1.0pt;" >, and <img src='/blog/wp-content/plugins/latexrender/pictures/130693682fe4d9d5612c6bc6f7df878f_1.0pt.gif' title='3^8' alt='3^8'  style="vertical-align:-1.0pt;" > are the only possible powers that can be equal to one. We will call this the <strong>generator test</strong>. We can check these particular values quickly through successive squaring. If any of the powers of 3 less than 8 are congruent to 1, then we have a failure, and it is not a generator.</p>
<p>If you do not have access to a good way to factor p-1, the following naive method will work well for small numbers. Please note that the preferable way is to factor p-1 and to find all of the divisors of p-1 that way.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">// ***********************************************************************</span>
<span style="color: #666666;">// Precondition: p is a prime. If it is not, it will return 0 indicating</span>
<span style="color: #666666;">// failure</span>
<span style="color: #666666;">//</span>
<span style="color: #666666;">// This assumes that you are trying to do this for a small p, without being</span>
<span style="color: #666666;">// able to factorize p-1 quickly.</span>
<span style="color: #666666;">// ************************************************************************</span>
<span style="color: #0000ff;">unsigned</span> <span style="color: #0000ff;">int</span> find_generator<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> p<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
  <span style="color: #0000ff;">int</span> phi_p<span style="color: #008000;">&#40;</span>p<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
  std<span style="color: #008080;">::</span><span style="color: #007788;">vector</span> test_powers<span style="color: #008080;">;</span> 
&nbsp;
  <span style="color: #0000ff;">int</span> i<span style="color: #008080;">;</span> 
&nbsp;
  <span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span>i<span style="color: #000080;">=</span><span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> i
<span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span><span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> <span style="color: #000040;">--</span>i<span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>powmod<span style="color: #008000;">&#40;</span>test, test_powers<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span>, p<span style="color: #008000;">&#41;</span> <span style="color: #000080;">==</span> <span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
	      found <span style="color: #000080;">=</span> <span style="color: #0000ff;">false</span><span style="color: #008080;">;</span>
	      <span style="color: #0000ff;">break</span><span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span>
      <span style="color: #008000;">&#125;</span> 
&nbsp;
      <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>found<span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
	  <span style="color: #0000ff;">return</span> test<span style="color: #008080;">;</span>
      <span style="color: #008000;">&#125;</span>
   <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h3>So what?</h3>
<p>If we have an element a (mod n) who has <img src='/blog/wp-content/plugins/latexrender/pictures/d16434743153552f195e740c1f93bd26_1.0pt.gif' title='a^{n-1} = 1' alt='a^{n-1} = 1'  style="vertical-align:-1.0pt;" >, and <img src='/blog/wp-content/plugins/latexrender/pictures/433d6e4ef1439c920d75200519547732_1.0pt.gif' title='a^{positive\ integer\ less\ than\ n}' alt='a^{positive\ integer\ less\ than\ n}'  style="vertical-align:-1.0pt;" > is not equal to 1, we have a<strong> generator</strong>. The generator is for a set of integers of size (p-1), which is even.</p>
<h3>Finding generators is nontrivial</h3>
<p>A downside to this method is that there is no free lunch when it comes to finding generators. You have to find one, although fortunately for us, most numbers have generators that are less than 10, so you can find them by linearly searching. There are a few strategies of how we can pick primes that will allow us to (relatively) quickly find a generator (mod p). The one I use is:</p>
<p>One strategy is finding a prime, <em>p</em>, such that <em>q = </em>2*<em>p</em> + 1 is also prime. The only two numbers that you have to check that violate our generator condition are 2 and p, in which case <em>q</em> is a generator. This helps reduce the complexity of the test. How do we know if our numbers are prime? Probabilistic primality testing, of course <img src='http://www.jakevoytko.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . It&#8217;s amazing how all of this stuff ties together.</p>
<p>A professor I had for a cryptology course said that the odds of the first generator NOT being less than 10 has been shown to be inordinately small, but I can&#8217;t for the life of me find any sort of reference to a figure that states that. As there is no trivial way to find a hash function, it is acceptable to search for the first generator (mod p) linearly, using our generator test, if you are looking for just any generator of p. Likewise, you can also find the largest such generator (mod p) by reverse searching.</p>
<p><strong>This is so complicated. Why would I use this over a linear hash?</strong></p>
<ul>
<li>The elements selected are not at a fixed interval, so data is usually less likely to cluster, which results in fewer collisions</li>
<li>It does better at the <strong>avalanche test</strong>, which says that when a bit of the input changes, at least half of the bits of the output should change. The linear hash fails miserably at this, and geometric hashes (depending on your generator, of course), perform better than their linear counterparts.</li>
</ul>
<p>Sometime in the future, (not in the next post, though), I will develop benchmarks to see what is better to deal with various different input scenarios. There&#8217;s no sense in developing the mathematics if we don&#8217;t actually put it all on the line and see if the &#8220;better&#8221; method works better in the real world. The real world has an amazing way of yelling &#8220;surprise!&#8221;, but we can limit that surprise through testing, testing, testing.</p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=15&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2007/09/30/number-theory-hash-tables-and-geometric-progressions/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Number Theory for Programmers, Part 2</title>
		<link>http://www.jakevoytko.com/blog/2007/09/23/number-theory-for-programmers-part-2/</link>
		<comments>http://www.jakevoytko.com/blog/2007/09/23/number-theory-for-programmers-part-2/#comments</comments>
		<pubDate>Sun, 23 Sep 2007 21:40:46 +0000</pubDate>
		<dc:creator>Jake</dc:creator>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[GCD]]></category>
		<category><![CDATA[Greatest Common Divisor]]></category>
		<category><![CDATA[Hash]]></category>
		<category><![CDATA[Hash table]]></category>
		<category><![CDATA[Number Theory]]></category>

		<guid isPermaLink="false">http://www.jakevoytko.com/blog/2007/09/23/number-theory-for-programmers-part-2/</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 Those who are interested [...]]]></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>
<ul>
<li>Those who did not know the answer to the above question</li>
<li>Those who are interested in the math behind hash functions</li>
<li>Those who found my last article interesting</li>
</ul>
<h3>What will this article focus on?</h3>
<p>This article will focus on using the integers (mod <em>n</em>) as indices of a <a href="http://en.wikipedia.org/wiki/Hash_table">hash table</a>, and the math behind different choices of hash functions. Our goal is to find a &#8220;good&#8221; hash function (see below). The mathematical explanation will be done irrespective of Group Theory, and I may write another article to look at a hash table as a group over addition or multiplication of the integers (mod <em>n</em>). For a quick refresher of the (mod <em>n</em>) concept, go <a href="http://www.jakevoytko.com/blog/2007/09/16/number-theory-for-programmers-part-1/">here</a>, or for another explanation, please look <a href="http://www.math.csusb.edu/notes/rel/node4.html">here</a>.</p>
<h3>Useful Tools</h3>
<h3>Greatest Common Divisor (GCD) of positive integers</h3>
<p><strong>Explanation:</strong></p>
<p>Mathematically, the greatest common divisor of two numbers a and b is the product of all common divisors of a and b. For a simple explanation as to why, look <a href="http://en.wikipedia.org/wiki/Euclidean_algorithm#Proof">here</a>.</p>
<p><strong>The Algorithm:</strong></p>
<p><strong>Naive</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">unsigned</span> <span style="color: #0000ff;">int</span> gcd<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">unsigned</span> <span style="color: #0000ff;">int</span> a, <span style="color: #0000ff;">unsigned</span> <span style="color: #0000ff;">int</span> b<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">int</span> remaind<span style="color: #008080;">;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">!</span>a<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">return</span> b<span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span> <span style="color: #666666;">// gcd(a, 0) = a</span>
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">!</span>b<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span><span style="color: #0000ff;">return</span> a<span style="color: #008080;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>a <span style="color: #000040;">&amp;</span>lt<span style="color: #008080;">;</span> b<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        a <span style="color: #000040;">^</span><span style="color: #000080;">=</span> b<span style="color: #008080;">;</span>  <span style="color: #666666;">// Swap a and b in place</span>
        b <span style="color: #000040;">^</span><span style="color: #000080;">=</span> a<span style="color: #008080;">;</span>
        a <span style="color: #000040;">^</span><span style="color: #000080;">=</span> b<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">while</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>remaind <span style="color: #000080;">=</span> a <span style="color: #000040;">%</span> b<span style="color: #008000;">&#41;</span> <span style="color: #000040;">&amp;</span>gt<span style="color: #008080;">;</span> <span style="color: #0000dd;">0</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        a <span style="color: #000080;">=</span> b<span style="color: #008080;">;</span>
        b <span style="color: #000080;">=</span> remaind<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0000ff;">return</span> b<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p><strong>Binary: </strong>(It&#8217;s <strong>always</strong> worth it to try to find the algorithms that take advantage of working with bits. If life gives you an integer as the sum of powers of two, make lemonade <img src='http://www.jakevoytko.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> )</p>
<p>Wikipedia has a <a href="http://en.wikipedia.org/wiki/Binary_GCD_algorithm">page</a> that explains a binary algorithm that takes advantage of the binary format of the data. It reduces the problem by stripping out common multiples of two, and then applying the binary analogy of the GCD algorithm. For more details, follow the above link. I haven&#8217;t benchmarked it, but it relies heavily on bit operations, so it should run a little faster on modern popular architectures.</p>
<h3>Least Common Multiple (LCM) of positive integers</h3>
<p><strong>Explanation:</strong></p>
<p>The least common multiple is as it sounds: the smallest multiple that both <em>a</em> and <em>b</em> share. For example:<br />
LCM(15, 20) = 60.</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/cb3e98c4c0a1ad7600b28db8a0587ce6_1.0pt.gif' title=' 15 = 3^{1} * 5^{1} ' alt=' 15 = 3^{1} * 5^{1} '  style="vertical-align:-1.0pt;" ><br />
<img src='/blog/wp-content/plugins/latexrender/pictures/25f505db899a6b15e31310cfe2837b22_1.0pt.gif' title='20 = 2^{2} * 5^{1}' alt='20 = 2^{2} * 5^{1}'  style="vertical-align:-1.0pt;" ><br />
<img src='/blog/wp-content/plugins/latexrender/pictures/8fd773a9cfb91b509f5943cfeed1ae0d_1.0pt.gif' title='60 = 3^{1} * 2 ^{2} * 5^{1}' alt='60 = 3^{1} * 2 ^{2} * 5^{1}'  style="vertical-align:-1.0pt;" ></p>
<p>It appears that for each prime, the LCM of <em>a</em> and <em>b</em> includes the largest power from either <em>a</em> or <em>b</em>. In fact, this is true.</p>
<h3>Relation between GCD and LCM</h3>
<p>For integers a and b:</p>
<p><img src='/blog/wp-content/plugins/latexrender/pictures/ed271db0080f343fce6f6125b77c3872_3.5pt.gif' title='LCM(a, b)\ *\ GCD(a, b)\ =\ a\ *\ b' alt='LCM(a, b)\ *\ GCD(a, b)\ =\ a\ *\ b'  style="vertical-align:-3.5pt;" ></p>
<p>This is very powerful, and lets us efficiently calculate the LCM of a and b by dividing out the GCD of a * b. Why does this work? If <em>a</em> and <em>b</em> don&#8217;t have any prime factors in common, clearly the only way that we can have a multiple of <em>a</em> equal some multiple of <em>b</em> is by multiplying <em>b</em> by <em>a</em>. If <em>a</em> and <em>b</em> only have one prime factor in common (let&#8217;s call it <em>d</em>), if you multiply <em>a</em> by <em>b</em>, we get a*b as an answer. However, (a*b)/d is clearly a multiple of both <em>a</em> and <em>b</em>. We don&#8217;t need to multiply <em>a</em> by <em>d</em>, since <em>a</em> already HAS <em>d</em> as a factor. <em>d</em> is uncoincidentally the GCD of <em>a</em> and <em>b</em>, and clearly, GCD(a, b) * LCM(a, b) = a * b. An actual proof is left as an exercise to the reader.</p>
<h3>What makes a good hash // hash table?</h3>
<p>The short answer is that nobody knows. Hashes that work well for some kinds of inputs can produce intractable results for other kinds of input. For our purposes, we will say that a good hash function minimizes the odds of two different inputs ending up in the same congruence class (mod <em>n</em>). When two different inputs DO end up in the same index, this is called a <strong>collision</strong>, and is as undesirable in hash tables as it is while driving. Also bad is <strong>clustering</strong>, which is when collisions are much more likely to happen in certain indices than in other indices.</p>
<p>Ideally, we would like the hash function to be able to place elements at any index in the table. This makes it a <strong>generator</strong>, namely, it can generate any value in the table.</p>
<p>We will try to find a happy medium of all concerns through experimentation. I will define a few different hash functions in the upcoming articles, and then will show how to compare them. That will be where the &#8220;<a href="http://www.xkcd.com/store/try_science_shirt_300.png">Science</a>&#8221; part of Computer Science enters the picture <img src='http://www.jakevoytko.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Linear Hashes<br />
</strong></p>
<p>Linear hashes take in some number <em>x</em>, and place the object in the index <em>ax </em>+ <em>b </em>(mod <em>n</em>). To make the mathematics easier, we will just use <em>ax</em>(mod <em>n</em>), as it should be obvious that adding <em>b</em> produces the set in the same order, but with a different starting point. In order for us to consider <em>a</em> as a hash function, <em>a</em> must be a generator (mod <em>n</em>). How do we know that it does that? Let&#8217;s look at a few different values of <em>a</em> (mod 16).</p>
<p><em><img src='/blog/wp-content/plugins/latexrender/pictures/701067ed5d646af1c269d1bb85bd3e69_1.0pt.gif' title='2^1 = 2' alt='2^1 = 2'  style="vertical-align:-1.0pt;" > </em>: {2, 4, 6, 8, 10, 12, 14, 0, 2} (mod 16) (doesn&#8217;t generate the integers (mod 16))</p>
<p><em><img src='/blog/wp-content/plugins/latexrender/pictures/d7b213cee95b4b6b3ab6b90cadfed175_1.0pt.gif' title='3^1' alt='3^1'  style="vertical-align:-1.0pt;" > = 3</em>: {3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 9, 12, 15, 3} (mod 16) (generates the integers (mod 16))</p>
<p><em>2*3 = 6</em>: {6, 12, 2, 8, 14, 4, 10, 0, 6} (mod 16) (doesn&#8217;t generate the integers (mod 16)).</p>
<p>So what works? It works when gcd(<em>a</em>, <em>n</em>) = 1. This is known as being <strong>relatively prime</strong> or <strong>coprime</strong>, meaning they don&#8217;t share any common prime factors. <img src='/blog/wp-content/plugins/latexrender/pictures/d7b213cee95b4b6b3ab6b90cadfed175_1.0pt.gif' title='3^1' alt='3^1'  style="vertical-align:-1.0pt;" > and <img src='/blog/wp-content/plugins/latexrender/pictures/27eac782422adb62c41a6f3c2c99a5d1_1.0pt.gif' title='2^4' alt='2^4'  style="vertical-align:-1.0pt;" > obviously don&#8217;t share any prime factors, so 3 is a generator using addition (mod 16).</p>
<p>Why does that work?  The largest possible multiple of a that will give us 0 (mod n) is n, because a*n == a * 0 == 0 (mod n). We need to make the LCM of a and n equal to a * n, and since we know that LCM(a, n) = a * n / GCD(a, n), it follows that GCD(a, n) = 1.</p>
<p>Since most hash tables you make will have 2^n elements (this seems to be the standard, for addressing reasons), any odd number <em>a</em> will suffice to be a generator for linear hashes.</p>
<p><strong>Theoretically, which hash value should I use?</strong></p>
<p>Linear hashing is obviously a very simple hash function (the simplest one there is, I believe), and therefore, there is not a single hash fucntion that will work for every input set. In fact, this type of hash will have many input sets that will make it have very poor performance. However, if we have advanced knowledge of the kind of data that will be the input, we can stack the deck in our favor.</p>
<p>If your data is guaranteed to have no collisions (mapping unique integers less than the size of the hash table to some value), you can use any positive integer you want as your hash. I recommend 1 for ease of calculation <img src='http://www.jakevoytko.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>If your data is sorted ascending, use hash values close to 1. If you can find the mode of the data in advance, you can yourself by setting the hash value larger than the mode. If the mode is large with respect to the size of the hash table or with respect to the size of the data set, you can make the hash value larger than the average number of repetitions for each input.</p>
<p>If your data is sorted descending, you want to do as above, except make your hash value close to n-1. The reasoning can be derived from the above paragraph.</p>
<p>If your data is either purely random, or of several different varieties, your hash function is not always going to work no matter how hard you try. We should avoid hashes close to <em>1</em> and <em>n-1, </em>but other than that, we will need to benchmark to see if there is a better value.</p>
<p><script type="text/javascript"><!--
  amazon_ad_tag = "jakvoyshom-20";  amazon_ad_width = "468";  amazon_ad_height = "60";
// --></script><br />
<script src="http://www.assoc-amazon.com/s/ads.js" type="text/javascript"></script></p>
<img src="http://www.jakevoytko.com/blog/?ak_action=api_record_view&id=14&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.jakevoytko.com/blog/2007/09/23/number-theory-for-programmers-part-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<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>
