473,883 Members | 2,601 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why MULT 31 (hash function for string)?

Hi there,
There's a classic hash function to hash strings, where MULT is defined
as "31":

//from programming pearls
unsigned int hash(char *ptr)
{ unsigned int h = 0;
unsigned char *p = ptr;
int n;
for (n = k; n 0; p++) {
h = MULT * h + *p;
if (*p == 0)
n--;
}
return h % NHASH;
}

Why MULT defined as 31? ( How about 29? 24? or 26? )
Thanks,
Wenjie

Sep 19 '06
44 6770

In article <_K************ *************** ***@comcast.com >, Eric Sosman <es*****@acm-dot-org.invalidwrit es:
>
Engineer: 3 is prime, 5 is prime, 7 is prime, 9 is an
observational error, 11 is prime, ...
Like Richard Harter, I think the version I heard ascribes this one
to a Physicist.

The Engineer version I know goes something like: 3 is prime, 5 is
prime, 7 is prime, 9 is ... OK, we have a 25% defect rate.
Programmer: 3 is prime, 5 is prime, 7 is prime, 9 is
prime, 11 is prime, ...
I've seen Programmer given the "looping" answer, though I think it
looped on 7 ("7 is prime, 7 is prime, ..."), which IMO makes more
sense - the solution breaks when it reaches the first input that it
doesn't handle correctly.

Another Programmer answer might be: 3 is prime, 5 is prime, 7 is
prime. All the test cases pass - let's ship.

Like the various humorous versions of Dining Philosophers, lightbulb
jokes, and so forth, this seems to be a generative structure. Here
are some other possibilities, off the top of my head:

Executive: 3 is prime, 5 is prime, 7 is prime, 9 is prime (for
accounting purposes), ...

Marketer: 3 is prime, 5 is prime, 7 is prime, 9 is Prime 2.0!, ...

Rhetorician: 3 is prime, 5 is prime, 7 is prime. Let us pass over
9 in silence, and dwell no more on its merits or faults. 11 is
prime...

Multiculturalis t: 3 is prime, 5 is prime, 7 is prime. Excluding 9
from the primes would recapitulate the inequal relations inherent
in patriarchal-imperialist hegemony. Let us instead recognize that
9 is differently-primal.

Dadaist: 3 is prime, 5 is prime, 7 is prime, banana, 11 is prime...

--
Michael Wojcik mi************@ microfocus.com

"We are facing a dire shortage of clowns," said Erickson, also known as
Jingles.
Sep 21 '06 #41
ri*****@cogsci. ed.ac.uk (Richard Tobin) wrote:
# In article <ln************ ***@nuthaus.mib .org>,
# Keith Thompson <ks***@mib.orgw rote:
#
# >Computer scientist:
# 3 is prime, 5 is prime, 5 is prime, 5 is prime, 5 is prime, 5 is
# prime, 5 is prime, ...
#
# Typical programmer:
#
# 3 is prime, 5 is prime, 6.9999999998 is prime, ...

Prove that all odd integers higher than 2 are prime:
-Chemist: 3 is prime, 5 is prime, 7 is prime... hey, let's publish!

-Computer programmer: "3 is prime, 5 is prime, 7 is prime, 9 is... 3 is
prime, 5 is prime, 7 is prime, 9 is... 3 is..."
Um, right. Okay, how about this:
"3 is not prime, 5 is not prime, 7 is not prime, 9 is not prime..."
So much for the beta releases. Ship this:
"3 is prime, 5 is prime, 7 is prime, 9 is a feature, 11 is prime..." and
put on the cover "More prime numbers than anyone else in the industry!"

-Drunk: 3 is an odd prime, 5 is an odd prime, 7 is an odd prime,
9 is a very odd prime...

-Economist: 3 is prime, 5 is prime, 7 is prime, 9 is not prime. Look,
the prime rate is dropping!

-Engineer: 3 is prime, 5 is prime, 7 is prime, 9 is... 9 is... well,
if you approximate, 9 is prime, 11 is prime, 13 is prime...

-Engineer: 3 is prime, 5 is prime, 7 is prime, 9 is not working. Hand
me the pliers.

-New Yorker: 3 is prime, 5 is prime, 7 is prime, 9 is... NONE OF YOUR
DAMN BUSINESS!

-Physicist: 3 is prime, 5 is prime, 7 is prime, 9 is... uh, 9 is an
experimental error, 11 is prime, 13 is prime...

-Theologist: 3 is prime and that's good enough for me!

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Quit killing people. That's high profile.
Sep 22 '06 #42
>go****@yahoo.c om wrote:
>Why MULT defined as 31? ( How about 29? 24? or 26? )
In article <NJ************ *************** ***@comcast.com >
Eric Sosman <es*****@acm-dot-org.invalidwrot e:
[much snippage]
>... 31 may be attractive because it is close to a power of two,
and it may be easier for the compiler to replace a possibly slow
multiply instruction with a shift and subtract (31*x == (x << 5)
- x) on machines where it makes a difference. Setting MULT one
greater than a power of two (e.g., 33) would also be easy to
optimize, but might produce too "simple" an arrangement: mostly a
juxtapositio n of two copies of the original set of bits, with a
little mixing in the middle. So you want an odd MULT that has
plenty of one-bits.
I thought the same, some (ok, now "many") years ago, and suggested
trying both 31 and 33 back when the original Berkeley DB was being
written and tested.

On a number of sample data sets, it turns out that 33 performed
slightly better, given the way the hash value was used.

Because of the optimization issue (multiply into shift-and-add),
"multiply by 33 and add *p++" performed better than some other
"better" (in terms of bit distribution) algorithms. That is, the
other algorithms resulted in slightly fewer hash collisions, but
the time saved resolving such collisions was insufficient to make
up for the extra CPU time used calculating the more-complex hash
function.

Of course, this was in the 1990s, when 300 MHz was an amazingly
fast CPU. :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Sep 24 '06 #43
Chris Torek wrote:
Because of the optimization issue (multiply into shift-and-add),
"multiply by 33 and add *p++" performed better than some other
"better" (in terms of bit distribution) algorithms. That is, the
other algorithms resulted in slightly fewer hash collisions, but
the time saved resolving such collisions was insufficient to make
up for the extra CPU time used calculating the more-complex hash
function.
So what cpu is this that can shift by 5 then add (mult by 33) faster
than it can shift by 5 and subtract (mult by 31) ?
Regarding the performance of mod operations:
On the powerPCs I use at work division takes 19 cycles.

Sep 24 '06 #44
>Chris Torek wrote:
>Because of the optimization issue (multiply into shift-and-add),
"multiply by 33 and add *p++" performed better than some other
"better" (in terms of bit distribution) algorithms. That is, the
other algorithms resulted in slightly fewer hash collisions, but
the time saved resolving such collisions was insufficient to make
up for the extra CPU time used calculating the more-complex hash
function.
In article <11************ **********@m73g 2000cwd.googleg roups.com>,
Samuel Stearley <ny****@gmail.c omwrote:
>So what cpu is this that can shift by 5 then add (mult by 33) faster
than it can shift by 5 and subtract (mult by 31) ?
Hmm, I did realize, after I posted that, that what I wrote could
be misread that way. 33 produced *better* distributions (but only
very slightly) than 31, for the test data. So "h = (h*33) + c"
was better than "h = (h*31) + c". Other hash functions existed
that produced even-better distributions than either of those --
for instance, doing CRCs on the data -- but took sufficiently
longer, etc.
>Regarding the performance of mod operations:
On the powerPCs I use at work division takes 19 cycles.
If the division instruction (and/or registers; see, e.g., MIPS)
can "free run" while the CPU does other things, *and* the C
compiler is able to insert "useful" instructions between the
start of the "divide" operation and the use of its result, the
cycles required for division can sometimes be hidden. For most
hash algorithms, however, there is just not enough insertable
work:

hash = compute_hash(ke y);
entry_ptr = table[hash % tablesize];
... do stuff with *entry_ptr ...

Here, there are usually no more than two or three instructions'
worth of work to move, which will take only a cycle or two, leaving
most of those 19 as "not executed in parallel with anything".

It is worth adding that the Berkeley DB code uses (used?) a
"variable-size power-of-two mod via mask" on the result of the hash
in this case, via code much (but not exactly) like this:

SOMETYPE lookup(SOMETYPE 2 *table, const char *p) {
char *s;
unsigned char c;
unsigned int h;
SOMETYPE3 *entry_ptr;

for (h = 0; (c = *p) != 0; p++)
h = h * 33 + c;
entry_ptr = table->entries[h & table->mask];
while (entry_ptr != NULL)
if (entry_ptr->hash == h && strcmp(entry_pt r->key, p) == 0)
... found, stop looping ...
else
entry_ptr = entry_ptr->next;
}

(This is an "open chain" hash that is only suitable for in-memory
storage; Berkeley DB includes a bunch of methods that work better
for on-disk storage. The main advantage to open chain hashing is
that it is quite simple. In this case, the adjustable mask allows
the table size to be doubled whenever some desired "maximum load
factor" is exceeded.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Sep 24 '06 #45

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
14195
by: Damien Morton | last post by:
Ive been doing some investigation of python hashtables and the hash function used in Python. It turns out, that when running pystone.py, as much time is spent in string_hash() as is spent in lookdict_string(). If you look at python's hash function, shown below, you can get an idea why - a multiply is used for every character in the string. static long string_hash1(register char *p, int size)
3
3346
by: Markus Dehmann | last post by:
I have a class "Data" and I store Data pointers in an STL set. But I have millions of inserts and many more lookups, and my profiler found that they cost a lot of runtime. Therefore, I want to substitute the set<Data*> with a hash_set<Data*>: typedef hash_set<const Data*, hash<const Data*>, eqData> DataPointerHashSet; // typedef set<Data*> DataPointerHashSet; // (see complete code below) But it doesn't work! Everything is fine...
4
7263
by: flipdog | last post by:
Hello all, I didn't know there is a thread on hash function started in this newsgroup so reposted my posting from another group. Hope I can have some feedbacks. I am new to hash table. I came across a very well presented tutorial web page wrt hash table. In its content, it listed a number of hash functions which the web master(?) quoted from other web sites. So no explainations for these hash functions and I failed to understand a...
6
8284
by: barcaroller | last post by:
I'm looking for a hash function (in C) that will convert a string of arbitrary length (but less than 1024 chars) to a reasonably-unique 16-bit short integer. Can anyone point me to such a hash function?
6
17817
by: Frank King | last post by:
Hi, I am looking for a hash function to map string to string in VB. Could somebody give me some informtion? Thank you very much. fk
4
4916
by: yuyang08 | last post by:
Hello, everyone, I am wondering what is the hash function that is used in hash_map/hash_set. Can I replace it with my own hash function? Any comments on this? Thanks! -Andy
21
3921
by: Hallvard B Furuseth | last post by:
Is the code below valid? Generally a value must be accessed through the same type it was stored as, but there is an exception for data stored through a character type. I'm not sure if that applies in this case though: #include <limits.h> unsigned foo(void) { static const union { unsigned char str;
1
4894
by: aphrodite | last post by:
I have to write a program to manage a hash table using collision resolution by chaining, with numeric long integer and string keys and where the hash function should use polynomial accumulation. So...how exactly should I make this function? I understand all the other ways to make a hash function except this one. Laura
24
3322
by: Alexander Mahone | last post by:
Hello, I'm looking for an hash function to be used for an hash table that will contain structs of a certain kind. I've looked into Sourceforge.net, but so far I've found only hash functions for strings (string->index)...Do you know if there exist such a function somewhere? Thanks
0
9933
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9786
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10734
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10836
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9568
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7962
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5794
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5982
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3230
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.