Search code examples
prologfactorial

factorial by given number in prolog


How can I make a factorial in prolog by a given number ?

run:-write('This is a Prolog program that find the factorial of a number'),
start.
start:- nl,nl,write('Please enter the number X = '),read(X),
enterd(X). 
enterd(0):-
write('The factorial of a 0 is '),write('1'),nl.
enterd(X):-
X1 is X-1,
entered(X1,S),
R is S*X,

write('The factorial of the number is'),write(R),nl.

Solution

  • 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.