I am interested in finding a simple formula for determining the nth time a particular bit_count occurs in the sequence of natural numbers. Specifically, what is the relationship between K
and N
in the table below. So, for example, what is the N
of the K=123456789123456789123456789
, I can tell you the M
is 50
, but what is the N
?
length = 5for K in range(2**length): bits = bin(K)[2:].zfill(length) M = K.bit_count() # numbers of "1"s in the binary sequence N = sum(1 for i in range(K) if M==i.bit_count()) print(f'{K: <2}',bits,M,N)'''K bits M N0 00000 0 01 00001 1 02 00010 1 13 00011 2 04 00100 1 25 00101 2 16 00110 2 27 00111 3 08 01000 1 39 01001 2 310 01010 2 411 01011 3 112 01100 2 513 01101 3 214 01110 3 315 01111 4 016 10000 1 417 10001 2 618 10010 2 719 10011 3 420 10100 2 821 10101 3 522 10110 3 623 10111 4 124 11000 2 925 11001 3 726 11010 3 827 11011 4 228 11100 3 929 11101 4 330 11110 4 431 11111 5 0...'''
So, I appear to have solved half of it. It appears that
N = (K-sum(2**i for i in range(M)).bit_count()
whenever N<=M
. This appears to be because,
K = sum(2**i for i in range(M)) + sum(2**(M-1-i) for i in range(N))
again, whenever N<=M
. It appears that N<=M
occurs about half the time.
length = 5for K in range(2**length): bits = bin(K)[2:].zfill(length) M = K.bit_count() # numbers of "1"s in the binary sequence N = sum(1 for i in range(K) if M==i.bit_count()) if N <= M: A = sum(2**i for i in range(M)) + sum(2**(M-1-i) for i in range(N)) B = (K - sum(2**i for i in range(M))).bit_count() else: A = '-' B = '-' print(f'{K: <2}',bits,M,N,A,B)