home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.lang.c++:11329 comp.lang.c:11438
- Newsgroups: comp.lang.c++,comp.lang.c
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!wupost!m.cs.uiuc.edu!kale
- From: kale@m.cs.uiuc.edu (L. V. Kale')
- Subject: Re: Population count.
- Message-ID: <1992Jul22.170132.29418@m.cs.uiuc.edu>
- Organization: University of Illinois, Dept. of Comp. Sci., Urbana, IL
- References: <1992Jul14.133241.23637@ncsu.edu> <Bro0u3.4y0@watserv1.waterloo.edu> <1992Jul20.070613.23553@klaava.Helsinki.FI>
- Date: Wed, 22 Jul 1992 17:01:32 GMT
- Lines: 24
-
-
- Here is a simple code-fragement that counts the number of 1's in
- a word stored in x.
-
- int x, count;
- ...
- count = 0;
- while (x) { count++; x = x & (x-1); }
-
- Nice things about this: uses only two variable which can be expected to be in
- registers (unlike the lookup table).
- Also, loops only as many times as the number of ones. This is good
- for words with very few ones.
-
- The algorithm was taken from "Combinatorial Algorithms" book, by
- Reingold, Nievergelt and Deo.
- I used this in a primes-sieve program for counting the number of primes
- in a bitvector.
-
- --
-
- kale@cs.uiuc.edu
- L.V. Kale
- Dept. of Computer Science
-