Certainly! Here’s a Prolog program to calculate the factorial of a given number:
factorial(0, 1).
factorial(N, Result) :-
N > 0,
N1 is N - 1,
factorial(N1, SubResult),
Result is N * SubResult.
Explanation:
- The first clause of the
factorial
predicate states that the factorial of 0 is 1. - The second clause of the
factorial
predicate recursively calculates the factorial of a number N. It checks if N is greater than 0, subtracts 1 from N to get N1, recursively calculates the factorial of N1, and multiplies it with N to get the final result.
You can use the program by querying the factorial
predicate with a number. For example, to calculate the factorial of 5, you can execute the query:
factorial(5, Result).
The program will unify Result
with the factorial value, which in this case will be 120
.