Prolog factorial recursion

后端 未结 8 1833
無奈伤痛
無奈伤痛 2021-01-11 12:16

I\'m having trouble understanding the following factorial program

fact1(0,Result) :-
    Result is 1.
fact1(N,Result) :-
    N > 0,
    N1 is N-1,
    fac         


        
8条回答
  •  生来不讨喜
    2021-01-11 12:39

    non-tailer recursion :

     fact(0,1):-!. 
       fact(X,Y):- Z=X-1,
             fact(Z,NZ),Y=NZ*X.
    

    tailer recursion:

    fact(X,F):- X>=0,fact_aux(X,F,1).
    fact_aux(0,F,F):-!.
       fact_aux(X,F,Acc):- 
           NAcc=Acc*X, NX=X-1, 
        fact_aux(NX,F,NAcc).
    

提交回复
热议问题