Editorial for Funny Bits
Author:kahootist
Editorial
Let us go with the example where k=4, a=7, and n=2.
In other words, summing all positive integers that can be represented with at most k=4 bits with exactly n=2 bits that equal to 1, average it then round it down will get a=7.
Question 1: How many numbers are there where k=4 and n=2?**
We notice that there will be a total of 2k=2k=16 non-negative integers that can be represented with at most k=4 bits.
Each bit can be either set or unset (either 1 or 0). There are k=4 digits for each number, and we are choosing exactly n=2 of those bits to be set. This is a combination problem, and the number of ways to choose n bits out of k is given by the combination formula nCr(k,n)=nCr(4,2)=6.
Question 2: What is the sum of all numbers where k=4 and n=2?**
A brute-force solution that generates all required numbers then summing it could work for smaller numbers of n and k, but anything above n=15 would likely kill your computer.
Instead, we make a few observations:
- There are nCr(k,n)=6 numbers in total.
- Out of every single digit in all numbers, only n/k=50 of all digits will be set.
- For all nCr(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) bits set for every digit position. In other words, the sum of all numbers can be calculated as ∑i=0k−1(2i×kn×nCr(k,n))=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(nCr(k,n)∑i=0k−1(2i×kn×nCr(k,n)))=7
This formula can be further simplified to kn×(2k−1)=7.
Question 4: How do we find n from k and a?
Now that we have a formula that calculatees a from n and k, ignoring the floor function, the formula can be rearranged as n=2k−1a∗k. Adding a round function to this would pass all test cases.
Final Implementation
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.