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,

- factorial predicate with one argument N, that will calculate and N!
- 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

very poor

LikeLike

What is poor?

LikeLike

I want it by take number from user not in rule form

LikeLike

You can do that. First take an input from somewhere, them call the top level rule. This SO post has a quick overview on read rule: http://stackoverflow.com/questions/5107745/user-input-how-can-we-do-it

LikeLike

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

LikeLike