-1

In c++ I am searching for an efficient algorithm to generate all integers such that their binary representation is a subset of a set which is given by the binary representation of integer N. By efficient I mean that I don't want to for-loop through all integers smaller than N to check whether they are subsets, mainly because N could be very large.

An idea I had was to generate all possible subsets of an integer corresponding to the Hamming weight of N and then shift them to the correct positions using <<, but I am so far failing to find a good way how to do this.

Example:

For set 110100 given by integer N=52 all possible subsets would be:

{000100,010000,010100,100000,100100,110000}

corresponding to integers {4,16,20,32,36,48}, which is what I want to generate.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 1
    As-is the question is probably too broad for SO format. You should try the Computer Science SE or similar. Avoid cross posting. – Ron May 10 '18 at 10:33

1 Answers1

1

Let P be popcount(N), the number of bits that are set. The number of results is then 2P - 2.

Treat N as a boolean array (bits). For each bit which is set, generate two subsets: one with that bit set and one without it. This can be done recursively until no bits are set.

Finally, discard the original N from the results, and also 0 (as per your example).

The time complexity is linear in the size of the output, i.e. O(2P).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436