Editorial for Funny Bits


Author:kahootist

Editorial

Let us go with the example where k=4k = 4, a=7a = 7, and n=2n = 2.

In other words, summing all positive integers that can be represented with at most k=4k = 4 bits with exactly n=2n = 2 bits that equal to 11, average it then round it down will get a=7a = 7.

Question 1: How many numbers are there where k=4k = 4 and n=2n = 2?**

We notice that there will be a total of 2k=2k=162^{k} = 2^k = 16 non-negative integers that can be represented with at most k=4k = 4 bits.

Each bit can be either set or unset (either 11 or 00). There are k=4k = 4 digits for each number, and we are choosing exactly n=2n = 2 of those bits to be set. This is a combination problem, and the number of ways to choose nn bits out of kk is given by the combination formula nCr(k,n)=nCr(4,2)=6nCr(k, n) = nCr(4, 2) = 6.

Question 2: What is the sum of all numbers where k=4k = 4 and n=2n = 2?**

A brute-force solution that generates all required numbers then summing it could work for smaller numbers of nn and kk, but anything above n=15n = 15 would likely kill your computer.

Instead, we make a few observations:

  • There are nCr(k,n)=6nCr(k, n) = 6 numbers in total.
  • Out of every single digit in all numbers, only n/k=50n / k = 50% of all digits will be set.
  • For all nCr(k,n)=6nCr(k, n) = 6 numbers, each column of digits will have exactly the same number of set bits.

Knowing the above, we can deduce that there will be a total of nCr(k,n)∗(n/k)nCr(k, n) * \left(n / k\right) bits set for every digit position. In other words, the sum of all numbers can be calculated as ∑i=0k−1(2i×nk×nCr(k,n))=45\sum_{i = 0}^{k - 1}{\left( 2^{i}\times\frac{n}{k}\times\text{nCr}\left(k, n\right) \right)} = 45.

Question 3: How do we find the rounded-down average?

We have the sum and count from above. Dividing the sum by the count with a floor function attached to it would floor(∑i=0k−1(2i×nk×nCr(k,n))nCr(k,n))=7\text{floor}\left(\frac{\sum_{i = 0}^{k - 1}{\left( 2^{i}\times\frac{n}{k}\times\text{nCr}\left(k, n\right) \right)}}{\text{nCr}\left(k, n\right)}\right) = 7

This formula can be further simplified to nk×(2k−1)=7\frac{n}{k}\times{\left(2^{k}-1\right)}=7.

Question 4: How do we find nn from kk and aa?

Now that we have a formula that calculatees aa from nn and kk, ignoring the floor function, the formula can be rearranged as n=a∗k2k−1n = \frac{a * k}{2^{k} - 1}. Adding a round function to this would pass all test cases.

Final Implementation

Code 1
k, a = map(int, input().split())
print(round(a * k / ((1 << k) - 1)))

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.