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!