<?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; Hash</title>
	<atom:link href="http://www.jakevoytko.com/blog/tag/hash/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>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>
	</channel>
</rss>
