Python 2, 76 * 0.5 = 38
N=2**input()-1
v=N*2+1
while v:t=1+(v|~-v);v=N&t|~-(t&-t)//(v&-v)//2;print v^N
Repeatedly generates the next highest v
with the same POPCOUNT by this bit-twiddling algorithm.
Actually, it turned out easier to generate them in decreasing pop-count, then print the complement to make it increasing. That way, then v
overflows 2**n
, we simply remove all but n
bits with &N
where N=2**n-1
, and that gives the smallest number one popcount lower. That way, we can just do one loop. There's probably a better solution that directly finds the next lower number with the same POPCOUNT.
Due to a fencepost issue, we need to start with v=2**(n+1)-1
so that the operation produces v=N-1
on the first loop.
Output for 4
:
0
8
4
2
1
12
10
9
6
5
3
14
13
11
7
15