How to find all the numbers which are less than a given no and which have less no of set bits than the given no, but whatever no. of set bits each of the generated no has will be in the position same as the given no's set bit positions.Giving one example suppose the given no is 13 (1101 in binary),then all the generated no will be 12(1100 in binary),9 (1001 in binary),8(1000 in binary),5(0101 in binary),4(0100 in binary),1(0001 in binary). As it is visible that in 1100(set bit positions are 2 and 3 as in given no.1101). I want an efficient algorithm for this.
Asked
Active
Viewed 86 times
0
-
why not ten ? 1010? – Alberto Sinigaglia May 03 '20 at 13:25
-
Because in 1010 the set bit positions are 1 and 3 but in 13 (1101 in binary) there are no set bits in 1 position – glam videos opera May 03 '20 at 13:29
-
I want the generated no's set bit position as per the given no whatever no of set bits it has – glam videos opera May 03 '20 at 13:31
-
so you just want all the subset on the number composed by ones that are in the position where the original number ha them? you know that this number is huge? is something like 2^n where n is the number of bit set to 1 in the original one? – Alberto Sinigaglia May 03 '20 at 13:31
-
Should I have to generate all the subsequence of the set bit positions of the given no? – glam videos opera May 03 '20 at 13:35
-
The given condition of n is<=10^6 – glam videos opera May 03 '20 at 13:40
-
dependes on what you want to do, if you want to loop over them, is not that great to generate them and than loop over, it will cost a lot of memory to store them with big number – Alberto Sinigaglia May 03 '20 at 13:40
-
for example if you have 2^10-1 is nine 1, and so you can generate 2^10-1 number, with i doubt you want to store in a vector – Alberto Sinigaglia May 03 '20 at 13:41
-
I don't want to store them,I just want to use them for further calculation,the looping technique should be efficient enough so that it does not iterate over the unwanted values. – glam videos opera May 03 '20 at 16:12
2 Answers
0
std::vector<int> subset(int x) {
std::vector<int> res;
for(int i = 1; i < x; ++i)
if (i == (i&x))
res.push_back(i);
return res
}
It's complexity is optimal in the worst case (if x = 2^k-1
).

One Lyner
- 1,964
- 1
- 6
- 8
0
This seems to be equivalent to enumerating the subsets of the set defined by the set bits. This is answered here: https://stackoverflow.com/a/29043170/378360

Falk Hüffner
- 4,942
- 19
- 25