Sei sulla pagina 1di 9

# 5/12/12

## Program to count number of set bits in an (big) array | GeeksforGeeks

GeeksforGeeks
A computer science portal for geeks Home Q&A Interview Corner Ask a question Feedback Contribute About us Subscribe Arrays Articles Bit Magic C/C++ Puzzles GFacts Linked Lists MCQ Misc Output Strings Trees

## Program to count number of set bits in an (big) array

March 12, 2011 Given an integer array of length N (an arbitrarily large number). How to count number of set bits in the array? The simple approach would be, create an efficient method to count set bits in a word (most prominent size, usually equal to bit length of processor), and add bits from individual elements of array. Various methods of counting set bits of an integer exists, see this for example. These methods run at best O(logN) where N is number of bits. Note that on a processor N is fixed, count can be done in O(1) time on 32 bit machine irrespective of total set bits. Overall, the bits in array can be computed in O(n) time, where n is array size.
www.geeksforgeeks.org/archives/11263 1/9

5/12/12

## Program to count number of set bits in an (big) array | GeeksforGeeks

However, a table look up will be more efficient method when array size is large. Storing table look up that can handle 232 integers will be impractical. The following code illustrates simple program to count set bits in a randomly generated 64 K integer array. The idea is to generate a look up for first 256 numbers (one byte), and break every element of array at byte boundary. A meta program using C/C++ preprocessor generates the look up table for counting set bits in a byte. The mathematical derivation behind meta program is evident from the following table (Add the column and row indices to get the number, then look into the table to get set bits in that number. For example, to get set bits in 10, it can be extracted from row named as 8 and column named as 2),
0 1 2 3 , , , 0-0 1 1 2---- GOPA0 , , , ---- RU_() 4-1 2 2 3---- GOPA1 , , , ---- RU_() 8-1 2 2 3---- GOPA1 , , , ---- RU_() 1 -2 3 3 4---- GOPA2 2 , , , ---- RU_() 1 -1 2 2 3---- GOPA1 6 , , , ---- RU_() 2 -2 3 3 4---- GOPA2 0 , , , ---- RU_() 2 -2 3 3 4---- GOPA2 4 , , , ---- RU_() 2 -3 4 4 5---- GOPA3 ..s o 8 , , , ---- RU_() . o n

From the table, there is a patten emerging in multiples of 4, both in the table as well as in the group parameter. The sequence can be generalized as shown in the code. Complexity: All the operations takes O(1) except iterating over the array. The time complexity is O(n) where n is size of array. Space complexity depends on the meta program that generates look up. Code: #nld <ti.> icue sdoh #nld <tlbh icue sdi.> #nld <ieh icue tm.> / Sz o ary6 K* * ie f ra 4 / #eieSZ ( < 1) dfn IE 1 < 6 / Mt pormta gnrtsstbtcut * ea rga ht eeae e i on aryo frt26itgr * ra f is 5 nees / / GOPA-We cmie wt MT_OKU * RU_ hn obnd ih EALO_P gnrtscutfr44eeet * eeae on o x lmns /
www.geeksforgeeks.org/archives/11263 2/9

5/12/12

## Program to count number of set bits in an (big) array | GeeksforGeeks

#eieGOPAx x x+1 x+1 x+2 dfn RU_() , , , / GOPB-We cmie wt MT_OKU * RU_ hn obnd ih EALO_P gnrtscutfr444eeet * eeae on o xx lmns / #eieGOPBx GOPAx,GOPAx1,GOPAx1,GOPAx2 dfn RU_() RU_() RU_(+) RU_(+) RU_(+) / GOPC-We cmie wt MT_OKU * RU_ hn obnd ih EALO_P gnrtscutfr4444eeet * eeae on o xxx lmns / #eieGOPCx GOPBx,GOPBx1,GOPBx1,GOPBx2 dfn RU_() RU_() RU_(+) RU_(+) RU_(+) / Poieaporaelte t gnrt tetbe* * rvd prpit etr o eeae h al / #eieMT_OKU(AAEE)\ dfn EALO_PPRMTR GOP#PRMTR0, \ RU_#AAEE() GOP#PRMTR1, \ RU_#AAEE() GOP#PRMTR1, \ RU_#AAEE() GOP#PRMTR2 RU_#AAEE() \ itcuteBt(n ary] sz_ arysz) n onStisit ra[, iet ra_ie { itcut=0 n on ; / MT_OKU()-gnrtsatbeo 26itgr woe * EALO_PC eeae al f 5 nees hs sqec wl b nme o bt i it psto eune il e ubr f is n -h oiin wee0< i<26 hr = 5 * / / Asai tbewl b mc fse t acs * * ttc al il e uh atr o ces / sai usge ca cntlo_p]={MT_OKU()} ttc nind hr os oku[ EALO_PC ; / N sitn fna(o bte raaiiy * * o hfig ud fr etr edblt) / usge ca *Dt =NL; nind hr paa UL frsz_ idx=0 idx<arysz;idx+ o(iet ne ; ne ra_ie ne+) { / I i fn,bps tetp sse * * t s ie yas h ye ytm / paa=(nindca *&ra[ne] Dt usge hr )aryidx; / Cutstbt i idvda bts* * on e is n niiul ye / cut+ lo_ppaa0] on = oku[Dt[]; cut+ lo_ppaa1] on = oku[Dt[]; cut+ lo_ppaa2] on = oku[Dt[]; cut+ lo_ppaa3] on = oku[Dt[];

## rtr cut eun on;

www.geeksforgeeks.org/archives/11263 3/9

5/12/12

## Program to count number of set bits in an (big) array | GeeksforGeeks

} / Die porm gnrtstbeo rno 6 Knmes* * rvr rga, eeae al f adm 4 ubr / itmi( n an) { itidx n ne; itrno[IE; n admSZ] / Se t terno-ubrgnrtr* * ed o h admnme eeao / sad(nindtm(); rn(usge)ie0) / Gnrt rno nmes * * eeae adm ubr. / fr idx=0 idx<SZ;idx+) o( ne ; ne IE ne+ { rno[ne]=rn(; admidx ad) } pit(Ttlnme o bt =%\" cuteBt(adm SZ); rnf"oa ubr f is dn, onStisrno, IE) rtr 0 eun ;

Send 2 people

You may also like following posts 1. 2. 3. 4. 5. Count number of bits to be flipped to convert A to B Write an Efficient C Program to Reverse Bits of a Number Count set bits in an integer Rotate bits of a number Next higher number with same number of set bits

1. pranav says: October 13, 2011 at 7:57 PM please someone explain clearly GROUP_A, GROUP_B, etc. concept and meaning of the definition of :
www.geeksforgeeks.org/archives/11263 4/9

5/12/12

## Program to count number of set bits in an (big) array | GeeksforGeeks

#define META_LOOK_UP(PARAMETER) \ GROUP_##PARAMETER(0), \ GROUP_##PARAMETER(1), \ GROUP_##PARAMETER(1), \ GROUP_##PARAMETER(2) \ Reply Venki says: October 14, 2011 at 12:41 AM @pranav, the idea is to create table of 256 entries. The table contains number of set bits in the sequential index of table. The macro META_LOOK_UP(C) generates the table. After preprocessing stage the definition of look_up will be something like static unsigned char const look_up[] = { 0, 1, 1, 2, 1, 2, 2, 3, ... 6, 7, 7, 8 }; The code in main, simply splits the array into individual bytes and looks up the bit count value in the table. Reply

Comment
Name (Required) Website URI code between sourcecode tags) Email (Required) Your Comment (Writing code? please paste your

[oreoelnug=C] succd agae"" / Pseyu cd hr (o mydlt teelns * at or oe ee Yu a eee hs ie i ntwiigcd)* f o rtn oe / [succd] /oreoe

Search

www.geeksforgeeks.org/archives/11263

5/9

5/12/12

## Program to count number of set bits in an (big) array | GeeksforGeeks

Popular Tags
GATE Java Dynamic Programming Backtracking Pattern Searching Divide & Conquer Graph Operating Systems Recursion

Popular Posts
All permutations of a given string Memory Layout of C Programs Understanding extern keyword in C Median of two sorted arrays Tree traversal without recursion and without stack! Structure Member Alignment, Padding and Data Packing Intersection point of two Linked Lists Lowest Common Ancestor in a BST. Check if a binary tree is BST or not Sorted Linked List to Balanced BST

www.geeksforgeeks.org/archives/11263

6/9

5/12/12

250

Subscribe

## Forum Latest Discussion

LIS in nlogn time
Last Post By: kartik Inside: Interview Questions

tree to file
Last Post By: Dheeraj Inside: Interview Questions
www.geeksforgeeks.org/archives/11263 7/9

5/12/12

## Count internal nodes in a binary tree

Last Post By: kartik Inside: Interview Questions

## Ancestor of two given leaf nodes

Last Post By: dead Inside: Trees specific questions

## combine elements of an array, so as to minimize weights.

Last Post By: rohanag Inside: Interview Questions

FB interview question
Last Post By: ranganath111 Inside: Interview Questions

## Testing of factorial of a number

Last Post By: rukawa Inside: Interview Questions

numeric puzzle
Last Post By: asm Inside: Algorithms

Forum Categories
Interview Questions C/C++ Programming Questions Algorithms Trees specific questions Linked List specific questions Multiple Choice Questions Object oriented queries GPuzzles
www.geeksforgeeks.org/archives/11263 8/9

5/12/12

## Operating Systems Miscellaneous Java specific Questions Perl specific Questions

Venki on Structure Member Alignment, Padding and Data Packing avi on Structure Member Alignment, Padding and Data Packing atul on A Program to check if strings are rotations of each other or not Venki on Structure Member Alignment, Padding and Data Packing rahul on Dynamic Programming | Set 13 (Cutting a Rod) Sandeep on Dynamic Programming | Set 3 (Longest Increasing Subsequence) Yueming on Dynamic Programming | Set 3 (Longest Increasing Subsequence) avi on Structure Member Alignment, Padding and Data Packing @geeksforgeeks, Some rights reserved Powered by WordPress & MooTools, customized by geeksforgeeks team

www.geeksforgeeks.org/archives/11263

9/9