To response from Lucas Virgili explains well the reasoning behind the question (which is certainly even about binary representation), but I would like to give a somewhat more general answer:
When you take any number, in the abstract, and you represent that number in a groundwork, if you are just decomposing it into a series of smaller numbers. For example:
44 = 10*4 + 1*4 (base 10: 44)
= 16*2 + 1*12 (base 16: 2C)
= 32*1 + 16*0 + 8*1 + 4*1 + 2*0 + 1*0 (base 2: 101100)
And so on. In the case of binary numbers, there are only two possibilities: either the component is present or it is not:
1, 2, 4, 8, 16, 32,...
In the case of decimal numbers, for example, each component may occur from 0
to 9
times:
1,1,1,1,1,1,1,1,1, 10,10,10,10,10,10,10,10,10, 100,100,100,100,100,100,100,100,100, 1000...
And so on. To "mount" the number 44
, take 4 units (i.e. from 9 values 1
available take 4) and 4 tens (among the 9 values 10
available take up 4). No hundred, thousand, etc.
This reasoning is even true for "crazy" bases, such as: "represent an amount in Reais using as few notes/coins as possible":
1c,1c,1c,1c, 5c, 10c,10c, 25c, 50c, R$1, R$2,R$2, R$5, R$10,R$10, R$20, R$50, R$100...
R$44 = R$20 + R$10 + R$10 + R$2 + R$2
Reverse method
The most efficient way to solve this problem (representing a given number of components) is to start with the "largest of them" (or, if the sequence is infinite, the largest of them that is less than or equal to the number) and go through the list to the beginning - subtracting the values found until the number reaches zero:
entrada = 44
lista = [1,2,4,8,16,32,64,128]
maior = x in lista if x <= entrada
for y from maior to 0:
if y <= entrada:
incluir y na saída
entrada -= y
Except for the binary case (where the bit test is simpler and more efficient - since the computer "helps" you with the task with binary operators for this), this would be the best way to do, for an arbitrary input [ordered in ascending order, of course].
Direct method
Remember elementary school, when you learned to make sums using the QVL? The same principle can be used, but using an arbitrary basis instead of 10:
- As long as the value to be reached is greater than zero:
- Take the lowest value from the list (unit), and add it to the output - decreasing the input
- If the lowest value in the list is not available (i.e. all units were used), remove N values from the output and exchange them for a higher value (dec) - so that N units + 1 unit equals 1 dec.
- Repeat recursively for larger quantities (ten/hundred, hundred/thousand, etc).
I quoted this method out of curiosity only, because needless to say it is too inefficient (you would be "counting" from 1 to 44 - complexity O(n)
), I leave the implementation in code as exercise for the reader... : P
A similar algorithm could return the value 4+8+16+16?
– Weslley C X Sardinha
no. they cannot repeat themselves
– fsi