factorial(0, 1).
factorial(N, Result) :-
N > 0,
N1 is N - 1,
factorial(N1, Result1),
Result is N * Result1.
You can use this Prolog program to calculate the factorial of a number by calling factorial(N, Result)
, where N
is the number whose factorial you want to calculate, and Result
will be unified with the factorial result. For example:
?- factorial(5, Result).
Result = 120.