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?
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.