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?

7
  • Do you understand all the notations used? For example, do you know what X = X + 1 means? Commented Jul 20, 2013 at 16:43
  • Start by making a table of the values of X and Y for each round of the while loop asuming e.g. K = 5. Commented Jul 20, 2013 at 16:46
  • @ruakh yes that bit i understand, i guess the main bit i dont understand @ Terje D. is the k bit and how it works, thanks again Commented Jul 20, 2013 at 16:47
  • The code in the loop is repeated as long as X is not equal to K. For each round X is increased by one (and eventually becoming equal to K), and Y is multiplied by the new value of X. Commented Jul 20, 2013 at 17:09
  • The algorithm is wrong. Consider K=0, yet fac 0 = 1 per defintion. Commented Jul 20, 2013 at 19:04

3 Answers 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

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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 :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.