Prolog factorial recursion

后端 未结 8 1840
無奈伤痛
無奈伤痛 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:34

    Base case is declared. The conditions that N must be positive and multiply with previous term.

     factorial(0, 1).
     factorial(N, F) :- 
           N > 0, 
           Prev is N -1, 
           factorial(Prev, R), 
           F is R * N.
    

    To run:

    factorial(-1,X).

提交回复
热议问题