Search code examples
prologfactorial

How to calculate factorial using prolog


I have a code for calculating factorial as below :

fact(1,1).
fact(X,R):- X1 is X-1, fact(X1,R1), R is R1*X.

In my mind this code shouldn't work right but it does! What is my reason? I think when we call fact(3,R), first it calculate "X1 is X1 -1". Then it goes to next rule fact(X1,R1). This will call the goal part again and the code execution will return to the goal "fact(X,R)" and this will continue until we reach to fact(1,1). It means it never goes to R is R1*X part. So, it seems I am thinking wrong.

Can anyone tell me step by step about the code execution order in this code? Thanks


Solution

  • Once we "reach" the fact(1,1), it will "return" to the calling recursive iteration and proceed to the part R is R1*X of that iteration, with R1=1. Then will return again to a previous level and so on. Let's look at a non-trivial iteration:

    fact(3,R) :
       X <- 3,
       X1 <- 3-1 = 2,
       fact(2,R1) : 
          X' <- 2,
          X1' <- 2-1 = 1,
          fact(1, R1'), => R1'=1 (matched from fact(1,1)) 
          R'<- R1' * X' = 2
          R1 = R' = 2
       R <- R1*X = 2*3 = 6. 
    

    Here the variable with ' are denoting the variables corresponding to the fact(2,R) iteration. The variables without ' are for the topmost iteration.