2

L 语言由以下指令组成:

V <- V
V <- V+-1
IF V != 0 GOTO L, where each instruction may or may not have the label [L]

如何在 L 中编写阶乘函数?

4

1 回答 1

0

In what follows, I assume you are able to write functions with return statements. Otherwise, you can inline all functions and use new variables for local variables, and a new variable for the result. Returns should cause a new branch to after the function body. In other words, I use function/return syntax to reduce the complexity, not because it adds any power to the language.

One may object that I get things like recursion, etc., but I am not using that; looping is accomplished by GOTO. Subtact/Add functions could be combined into one, based on the sign of the second argument, so I see no harm in each calling the other. Combining these, and generally removing the function/return syntax, is left as an exercise.

(1) Write a sign function; returns 0 if 0, 1 if positive, and -1 if negative.

Sign(X)
 1. Y <- X
 2. Z <- X
 3. if Y=0 GOTO 8
 4. if Z=0 GOTO 10
 5. Y <- Y + 1
 6. Z <- Z - 1
 7. if 0=0 GOTO 3
 8. if Z=0 GOTO 11
 9. return -1
10. return +1
11. return 0

(2) Write addition and subtraction functions.

Add(X, Y)
 1. Sx = Sign(X)
 2. Sy = Sign(Y)
 3. if Sx=0 GOTO 13
 4. if Sy=0 GOTO 14
 5. SyP <- Sy + 1
 6. if SyP=0 GOTO 15
 7. Z <- Y
 8. R <- X
 9. R <- R + 1
10. Z <- Z - 1
11. if Z=0 GOTO 16
12. if 0=0 GOTO 9
13. return Y
14. return X
15. R <- Subtract(X, Y)
16. return R

Similarly for subtract.

(3) Write a multiplication function.

Multiply(X, Y)
 1. Sy = Sign(y)
 2. if Sy=0 GOTO 18
 3. SyP = Sy + 1
 4. if SyP=0 GOTO 12
 5. C <- Y
 6. R <- 0
 7. C <- C - 1
 8. R <- Add(R, X)
 9. if C=0 GOTO 11
10. if 0=0 GOTO 7
11. return R
12. C <- Y
13. R <- 0
14. C <- C + 1
15. R <- Subtract(R, X)
16. if C=0 GOTO 11
17. if 0=0 GOTO 14
18. return 0

(4) Write the factorial function.

Factorial(X)
 1. Sx = Sign(X)
 2. if Sx=0 GOTO 11
 3. SxP = Sx + 1
 4. if Sx=0 GOTO 11
 5. R <- 1
 6. C <- X
 7. R <- Multiply(R, C)
 8. C <- C - 1
 9. if C=0 GOTO 12
10. if 0=0 GOTO 7
11. return 1
12. return R

You may need to massage these to get them strictly following your formulation of L, but the ideas are sound (modulo silly errors I've introduced, writing in this language for the first time).

于 2013-01-28T23:13:09.097 回答