0

I've been given the following algorithm, that takes a positive integer K and returns a value:

X = 1
Y = 1
while X ≠ K do
    X = X + 1
    Y = Y * x
return Y

I'm supposed to figure out what it returns.

As it happens, I know the answer — it returns the factorial of K — but I don't understand why.

How do you go about figuring out what this pseudocode does?

4

3 回答 3

1
X = 1 <- this is counter which you gonna multiply in every step
Y = 1 <- this is to store the cumulative product after each step
while X ≠ K do <- until you reach K
    X = X + 1 <- increase X
    Y = Y * X <- multiply with increased X
return Y <- return the product

所以在循环中,累积产品是这样1 -> 1*2 - > 2*3 -> 6*4 -> ... -> 1*2*..*(K-1)*KK!

于 2013-07-20T16:54:51.733 回答
0

这段代码可以简单地重写为(在 C/C++/Java 中),

for(X=1;X<=K;X++){
    Y=Y*X;
}

现在它自我描述了:-)

于 2013-07-20T18:59:58.140 回答
0

现在假设 K 为 5。因此 5 的阶乘为 120。然后当您进入循环时,X 值为 2,y 的值为 2。(1*2)然后进入循环后 X 的值为 3,这使得 Y 的值为 6,因为 (3*2)。那么进入循环后X的值为4,这使得Y的值为24,因为(4 * 6)。然后进入循环后X的值为5,这使得Y的值为120。然后由于X==Y,while循环退出并返回作为阶乘的Y值。

于 2013-07-20T17:07:33.667 回答