I need to iterate over all n-bit integers in which no more than k bits are ON (bit 1), where 0 <n <= 32 and 0 <= k <= n. For example, if n = 4 and k = 2, then these numbers (in binary digits): 0000, 0001, 0010, 0100, 1000, 0011, 0101, 0110, 1001, 1010, 1100. The order in which these numbers are looping it doesn’t matter, but each of them is visited only once.
I am currently using this simple algorithm:
for x = 0 to (2^n - 1)
count number of bits 1 in x
if count <= k
do something with x
end if
end for
I think this algorithm is inefficient because it has to iterate over too many numbers. For example, if n = 32 and k = 2, then he must go through 2 ^ 32 numbers to find only 529 numbers (which have <= 2 bits 1).
My question is: is there a more efficient algorithm for this?