Prolog program to Calculate factorial of N


We know the formula for calculating n! (factorial of n)  is:

n! = n * (n-1)!

We can interpret this simple mathematical equation into a Prolog program. To do so, we must determine the basis of the recursion,

0! = 1

We will use two predicates here,

  1. factorial predicate with one argument N, that will calculate and N!
  2. factorial predicate with two arguments N and X. This function is recursively used. It will also calculate N!, but store it in the argument X in the process if recursion.

Code snippet given below is a sample program for the purpose.

predicates

factorial(integer,integer)
factorial(integer)

clauses

/* Base Case, 0!=1*/
factorial(0,X):-
X=1.
/* recursion for factorial */
factorial(N,X):-
NN=N-1,
factorial(NN,X1),
X=X1*N.
/*One argument function*/
factorial(N):-
factorial(N,X),
write(X).

Hope you will enjoy!

6 thoughts on “Prolog program to Calculate factorial of N

  1. my friend all the inputs are Out of local stack , thank you first of all but the factorial program you made is not efficient

    Like

    1. Here is a interesting thing: in Prolog, such recursion unfold in a different way than structured programming languages. This code was not written to be efficient, but to be expressive in a similar way to mathematics.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.