You do it the usual Prolog way - by defining a recursive rule that covers two clauses:
- When the number is
0
, its factorial is 1
- This can be done with a simple fact.
- When the number is greater than zero, compute
Number-1
, obtain its factorial, and multiplying the result by Number
.
This should not be too difficult to code up. All you need to know is that arithmetical operations use is
operator, i.e. PriorNum is Number - 1
or Result is Number * PriorFactorial
.
Your entered/1
predicate looks like an attempt. However, you should rework it into factorial/2
, with the first parameter representing the input, and the second parameter representing the output of your predicate.
No output should be happening in either of the two clauses - this should be done in the run
predicate.
factorial(0, 1).
factorial(X, R) :- N > 0, X1 is X-1, factorial(X1, S), R is S*X.
Demo.