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!

Advertisements

5 thoughts on “Prolog program to Calculate factorial of N

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s