Someone asked a question before the account: How many weights are required to claim 1 ~ 50g object?
This question has two variants:
1. At least how many weights (right code of the left object) are required to claim 1 ~ 50g object?
2. How much weight is required (the weight can be placed on any side) to claim 1 ~ 50g object?
The first question can be changed to: at least how many numbers can be added, which can represent 1 ~ Any number between 50. It can also evolve into: How to quickly retrieve the number you want from a bunch of apples?
The first question is that each number is in two states: Add or not. That is, the formula corresponding to is that for any number of X
X = 1 * A0 + 2 * A1 + 4 * a2... + 2 ^ K * ak (A0. .. ak can be 0 or 1)
This is also a common binary notation in the computer field. When all AI is set to 1, then 1 + 2 + 4... + 2 ^ K = 2 ^ (k + 1)-1> = x, bringing x = 50, k + 1 is what you want.
So the answer to the first question is log (50 + 1) rounded up.
This solves the first question, so the second question should be the variant of the first question.
Because the weight can be left, right, or not. There are three States (-, 0). This is how to identify a number with three states. So
X = 1 * A0 + 3 * A1 + 9 * A2 +... + 3 ^ K * ak where AI can take-1, 0, 1
When all AI is set to 1, then 1 + 3 + 9... + 3 ^ k = (3 ^ (k + 1)-1)/2> = x, bringing x = 50, then k + 1 is what you want
So the second answer is log3 (x * 2 + 1) rounded up to 5.
Before the account, I think of Fast Power-level operations.
A ^ K if A is multiplied by a, then K is required. If the binary method is used, you only need to multiply the log (k) to obtain the entire result.
A ^ 0 |
A ^ 1 |
A ^ 2 |
A ^ 3 |
A ^ 4 |
A ^ 5 |
1 |
A ^ 1 |
A ^ 2 |
A1 * a ^ 2 |
1 * a ^ 4 |
A ^ 1 * a ^ 4 |
In this way, we will find that a ^ K is actually in the binary format of K.
5 means 101 is a ^ 1 * a ^ 4
It is better to write the program below.
Total = 1; // total is the request, k is the power, and a is the base number while (k) {If (K & 1) Total * = A; A * =; k> = 1 ;}