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.
clauses/* Base Case, 0!=1*/
X=1./* recursion for factorial */
X=X1*N./*One argument function*/
Hope you will enjoy!
6 thoughts on “Prolog program to Calculate factorial of N”
What is poor?
I want it by take number from user not in rule form
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
my friend all the inputs are Out of local stack , thank you first of all but the factorial program you made is not efficient
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.