Hello All!
I am fairly new to c. In parts of my program I need to converts a very large number of consecutive integers to a binary, flip each bit while keeping track of the sum of bits and compute a weighted sum of the elements in a given array weighted by the bits.
Below is my solution. I what to improve the algorithm performance. Here are some ideas that I have. Maybe you can tell me which ones are good and how to implement them:
1. How can I find the value of the flipped bit so that I do not have to sum all the bits every time but increment an initial sum instead;
2. I heard of very efficient bit manipulation using masks (?) Does anyone have code that could be used in my program. Especially to sum the elements of the array (w)
3. The structure of my program allows splitting the outer loop in 2 or more threads. Would this help? If yes, how to do this.
Thank you very much for help!
Serge
Code:
#include <bitset>
#include <iostream>
int main()
{
static const unsigned n = 27;
static unsigned int w[ n ] = {10,12,10,4,12,29,7,27,4,7,29,29,12,12,7,29,7,4,4,3,13,27,12,14,7,4,10};
static const unsigned nc = 1 << n; /* 2^27 */
unsigned int sumv = 0;
unsigned int sumw = 0;
unsigned int i;
for ( i = nc; i--; ) /* loop through numbers from 2^27 to 0 */
{
std::bitset < n > v = i; /* binary representation of i */
unsigned int j;
for ( j = n ; j--; ) /* loop through bits */
{
v.flip( j ); /* flip the bit */
sumv = v.count(); /* compute the new sum of bits */
/* do other things */
/* compute weighted sum using flipped */
sumw = 0;
k = 0;
for ( k = n; k--; ) { if ( v[ n - k - 1 ] ) { sumw += w[ k ]; } }
printf( "%u\n" , sumw );
v.flip( j ); /* flip back */
}
}
return 0;
}