🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.arch
Article #12612

Re: % in hash table

#12612
From: Joe Buck
Date: Fri, 06 Oct 1995 02:03
43 lines
1745 bytes
colin@nyx10.cs.du.edu "Colin Plumb" writes:
>>word32 mod31(word32 x) ...

fred@genesis.demon.co.uk writes:
>This replaces 1 division operation with, at a rough count, 17 'fast'
>operations. While this may be faster on many systems it would be unwise
>to assume it.

While Colin's example can be improved, division does take upwards of 30
cycles on many architectures.  And there are faster cases:

(assume 32-bit int)

unsigned mod65537(unsigned x) {
	unsigned x1 = (x>>16);
	unsigned x2 = x&0xffff;
	/* note x = x1*65536 + x2 = x1*65537 + x2 - x1 */
	/* so x mod 65537 = (x2-x1) mod 65537 */
	unsigned res = x2 - x1;
	if ((int)res < 0) res += 65537;
}

unsigned mod32767(unsigned x) {
	unsigned x1 = (x>>15);
	unsigned x2 = x&0x7fff;
	/* note x = x1*32768 + x2 = x1*32767 + x2 + x1 */
	/* so x mod 32767 = (x2+x1) mod 32767 */
	unsigned res = x2 + x1;
	/* but res could be as much as 2^17+2^15-2, so repeat */
	x1 = (res>>15); /* at most 4 */
	x2 = res&0xffff;
	res = x1 + x2;
	/* now res is at most 32767+4 */
	return (res < 32767) ? res : res - 32767;
}



-- 
-- Joe Buck 	<jbuck@synopsys.com>	(not speaking for Synopsys, Inc)
Anagrams for "information superhighway":	Enormous hairy pig with fan
						A rough whimper of insanity
Technical Details
Message-ID: <4522pb$cid@hermes.synopsys.com>
Path: arc1-ca.pugleaf.net!news.synopsys.com!jbuck
References: <43tqr6$3au@mikasa.iol.it> <44t2n7$oe1@bug.rahul.net> <44ttt5$s8r@nyx10.cs.du.edu> <812838189snz@genesis.demon.co.uk>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!news.synopsys.com!jbuck
From: jbuck@synopsys.com (Joe Buck)
Newsgroups: comp.arch,comp.arch.arithmetic,comp.lang.c
Subject: Re: % in hash table
Date: 6 Oct 1995 02:03:23 GMT
Organization: Synopsys Inc., Mountain View, CA 94043-4033
Message-ID: <4522pb$cid@hermes.synopsys.com>
References: <43tqr6$3au@mikasa.iol.it> <44t2n7$oe1@bug.rahul.net> <44ttt5$s8r@nyx10.cs.du.edu> <812838189snz@genesis.demon.co.uk>
NNTP-Posting-Host: deerslayer.synopsys.com