Reputation: 15
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?
Upvotes: 0
Views: 10634
Reputation: 4565
this piece of code can be simply rewritten as (in C/C++/Java),
for(X=1;X<=K;X++){
Y=Y*X;
}
Now it describes it self :-)
Upvotes: 0
Reputation: 438
Now let's assume that K is 5. Therefore the factorial of 5 is 120. Then as you enter the loop X value is 2 and y gets the value 2.(1*2) Then the value of X is 3 after getting into loop, which then makes the value of Y 6 because (3*2). Then the value of X is 4 after getting into loop, which then makes the value of Y 24 because (4*6). Then the value of X is 5 after getting into loop, which then makes the value of Y 120. Then since X==Y the while loop exits and Y value which is the factorial is returned.
Upvotes: 0
Reputation: 1399
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
So in the loop the cumulative product goes like this 1 -> 1*2 - > 2*3 -> 6*4 -> ... -> 1*2*..*(K-1)*K
which is K!
Upvotes: 1