Article View: comp.arch
Article #12603Re: % in hash table
From: Colin Plumb
Date: Wed, 04 Oct 1995 12:15
Date: Wed, 04 Oct 1995 12:15
43 lines
2271 bytes
2271 bytes
In article <44t2n7$oe1@bug.rahul.net>, Samuel P. Kho <samkho@rahul.net> wrote:
> could you describe how to take modulo-prime-number-1-less-than-2^n by
> few shifts and adds over mod 2^n?
Sure! It's the same way you find numbers modulo 9 in base 10: add up the
digits. Or the way you find them modulo 11, by alternating adding and
subtracting.
For example, let's say I want a 32-bit number modulo 31. That's 2^5-1,
and it takes 7 5-bit fields to fill up a 32-bit number, so we'll reduce
logarithmicly, in three steps:
word32 mod31(word32 x)
{
/* First, 5*4 = 20 bits, and add 1 to prevent 0 result */
x = (x & 0xfffff) + (x >> 20) + 1;
/* Then 10 bits */
x = (x & 0x3ff) + (x >> 10);
/* Then 5 bits */
x = (x & 0x1f) + (x >> 5); /* 1 <= Result <= 0x3f */
/* Then fold back in any overflow and subtract the extra 1 */
x = (x & 0x1f) + (x >> 5); /* 1 <= Result <= 0x20 */
x = (x & 0x1f) + (x >> 5) - 1; /* 0 <= Result <= 0x1e */
}
The idea is based on the fact that 32*x is congruent to x mod 31.
So if I take some bits and shift them 5 (or a multiple of 5) bits down
and add them to the remaining bits, I haven't changed the value,
modulo 31.
The only tricky part is figuring out the number of final fold-back
steps required, or maybe finding a way to structure the computation
so fewer are needed. The +1/-1 part (where the +1 gets added is not too
critical) is because the fold-and-add reduces numbes to the range 1..31
(except for an input of zero), and we want an output range of 0..30.
The last little bit is kind of tricky to nail down = perhaps someone
who's thought about it more can suggest a more efficient algorithm?
(There are variations on this for 2^n-k, for small k, although
they get more complex.)
--
-Colin
Technical Details
Message-ID:
<44ttt5$s8r@nyx10.cs.du.edu>Path:
arc1-ca.pugleaf.net!nyx10.cs.du.edu!not-for-mailReferences:
<43tqr6$3au@mikasa.iol.it> <jgkDFv094.JKJ@netcom.com> <44sjp4$c71@news.jf.intel.com> <44t2n7$oe1@bug.rahul.net>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!nyx10.cs.du.edu!not-for-mail From: colin@nyx10.cs.du.edu (Colin Plumb) Newsgroups: comp.arch,comp.arch.arithmetic,comp.lang.c Subject: Re: % in hash table Date: 4 Oct 1995 06:15:33 -0600 Organization: University of Denver, Dept. of Math & Comp. Sci. Message-ID: <44ttt5$s8r@nyx10.cs.du.edu> References: <43tqr6$3au@mikasa.iol.it> <jgkDFv094.JKJ@netcom.com> <44sjp4$c71@news.jf.intel.com> <44t2n7$oe1@bug.rahul.net> NNTP-Posting-Host: nyx10.cs.du.edu Keywords: hash