Description
StartingXAnd repeatedly multiplyingX, We can computeX31 with thirty multiplications:
X2 =X×X,X3 =X2 ×X,X4 =X3×X,...,X31 =X30 ×X.
The operation of squaring can be appreciably shorten the sequence of multiplications. The following is a way to computeX31 with eight multiplications:
X2 =X×X,X3 =X2 ×X,X6 =X3×X3,X7 =X6×X,X14 =X7×X7,X15 =X14×X,X30 =X15 ×X15,X31 =X30 ×X.
This is not the shortest sequence of multiplications to computeX31. There are always ways with only seven multiplications. The following is one of them:
X2 =X×X, X4 =X2 ×X2,X8 =X4×X4,X8 =X4×X4,X10 =X8 ×X2,X20 =X10 ×X10,X30 =X20×X10,X31 =X30 ×X.
If Division is also available, we can find a even shorter sequence of operations. It is possible to computeX31 with six operations (five multiplications and one Division ):
X2 =X×X,X4 =X2 ×X2,X8 =X4×X4,X16 =X8 ×X8,X32 =X16 ×X16,X31 =X32 bytesX.
This is one of the most efficient ways to computeX31 if a division is as fast as a multiplication.
Your mission is to write a program to find the least number of operations to computeXNBy multiplication and division startingXFor the given positive integerN. Products and quotients appearing in the sequence shocould beXTo a positive integer's power. In others words,X? 3, for example, shocould never appear.
Input
The input is a sequence of one or more lines each containing a single integerN.NIs positive and less than or equal to 1000. The end of the input is indicated by a zero.
Output
Your program shocould print the least total number of multiplications and divisions required to computeXNStartingXFor the integerN. The numbers shoshould be written each in a separate line without any superfluous characters such as leading or trailing spaces.
Sample Input
13170914735128119530
Sample output
06891191312
Source
Japan 2006
Idea: store the number obtained after each operation in an array, cut down the branches, and iterate more deeply. For details, see the code.
# Include <stdio. h> # define max (A, B) (A> B? A: B) int N, DEP, num [15]; bool DFS (INT CNT, int X) // X is the maximum number obtained after the last operation {If (Num [CNT] = N) return 1; if (CNT> = dep) return 0; X = max (x, num [CNT]); If (x * (1 <(DEP-CNT) <n) return 0; // if n is not obtained for the maximum number, the for (INT I = 0; I <= CNT; I ++) is returned directly) {num [CNT + 1] = num [CNT] + num [I]; If (DFS (CNT + 1, x) return 1; if (Num [CNT]> num [I]) num [CNT + 1] = num [CNT]-num [I]; else num [CNT + 1] = num [I]-num [CNT]; If (DFS (CNT + 1, x) return 1;} return 0 ;} int main () {whi Le (~ Scanf ("% d", & N) {If (n = 1) printf ("0 \ n"); else {num [0] = 1; for (DEP = 1; Dep ++) {If (DFS (0, 1) break;} printf ("% d \ n", DEP );}}}