I know that iterating over all subsets of a set of size n is a performance nightmare and will take O(2^n) time.
How about iterating over all subsets of size k (for (
You want Gosper's hack:
int c = (1<
Explanation:
Finding the next number with as many bits set basically reduces to the case of numbers with exactly one "block of ones" --- numbers having a bunch of zeroes, then a bunch of ones, then a bunch of zeroes again in their binary expansions.
The way to deal with such a "block of ones" number is to move the highest bit left by one and slam all the others as low as possible. Gosper's hack works by finding the lowest set bit (a
), finding the "high part" comprising the bits we don't touch and the "carry bit" (b
), then producing a block of ones of the appropriate size that begins at the least-significant bit.