A Solution: Playing with numbers
Consider the original binary bits, keep the bits in pairs of 2 for beginning.
First set each 2-bit field equal to the sum of the two single bits that were originally in the field. Then sum adjacent 2-bit fields, putting the results in each 4-bit field, and so on. The original problem (summing 16 bits) is divided into two problems (summing 8 bits), which are solved separately, and the results are added. The strategy is applied recursively, breaking the 8-bit fields into 4-bit fields, and so on.
So solving the above problem, the original number is 0xCF39. Write it down as binary keeping adjacent bit together as below.
11 00 11 11 00 11 10 01
As indicated earlier, sum up the pairs above (binary) and put the results back in the individual two bit fields as follows.
10 00 10 10 00 10 01 01
Now combine these numbers in blocks of 4 as follows and repeate the process of summing the two two bit numbers and putting the result back in the 4 bit fields as below.
1000 1010 0010 0101
0010 0100 0010 0010
Next, repeat the process by pairing the numbers in blocks of 8 and adding the two 4 bit numbers and placing the result back in the 8 bit block as below.
00100100 00100010
00000110 00000100
And lastly repeat the process by adding the two 8 bit numbers above and placing the result in the 16 bits as below and that is the sum of all the
1's in your original number i.e 0xCF39
0000000000001010 ----> Decimal 10.
The above strategy makes the original problem of summing 1's in a 16 digit number complete in 4 discrete steps. Point to note is that each of these steps of determining adjacent bits and summing them at each step can be done in parallel. Hence making the operation an order 4 operation ( i.e Log 2 (16) = 4 steps ).
It should be easy to write this recursive loop in any decent high level language... give it a shot!
Posted by insidemyhead [Personal] ( June 25, 2007 11:40 AM ) Permalink | Comments[0]

