Factorials in Prolog

segfaultlabs.com » Factorials in Prolog

Factorial

Note that I’ve done my best to avoid any mistakes in examples below, nevertheless I’m rather newbie to Prolog, so can’t fully guarantee they all are correct.

Images and definitions taken from Wikipedia and are under GNU Free Documentation License (GFDL).

The factorial function is formally defined by
Factorial
Implementation in Prolog :

factorial(0,1).
factorial(N,X) :- N>0, M is N-1, factorial(M,Y), X is N*Y.
e.g. factorial(4, F).

Double Factorial

n!! denotes the double factorial of n and is defined recursively by
Double factorial
Implementation in Prolog :
doublefactorial(N,1) :- N=0; N=1.
doublefactorial(N,X) :- N>1, M is N-2, doublefactorial(M,Y), X is N*Y.

e.g. doublefactorial(5, F).

Multifactorial

The double factorial is the most commonly used variant (look above), but one can similarly define the triple factorial (n!!!) and so on. In general, the k-th factorial, denoted by n!(k), is defined recursively as
Multifactorial
Implementation in Prolog :
multifactorial(N,K,1) :- N>=0, N<K.
multifactorial(N,K,X) :- N>=K, M is N-K, multifactorial(M,K,Y), X is N*Y.

e.g. multifactorial(6,2,F) which returns double factorial of 6.

Hyperfactorial

Hyperfactorial is a certain function on natural numbers that is related to the factorial. Generally written as H(n), it is defined as
Hyperfactorial
Implementation in Prolog: (I additionaly defined power rule as I couldn’t find it anywhere)
hyperfactorial(0,1).
hyperfactorial(N,Z) :- N>0, M is N-1, hyperfactorial(M,Y), power(N,N,S), Z is S*Y.
power(X,1,P) :- P is X.
power(X,2,P) :- P is X*X.
power(X,I,P) :- I>2, J is I-1, power(X,J,R), P is X*R.

e.g. hyperfactorial(3, F).

Superfactorial

Neil Sloane and Simon Plouffe defined the superfactorial in 1995 as the product of the first n factorials. Superfactorial
Implementation in Prolog :
factorial(0,1).
factorial(N,F) :- N>0, M is N-1, factorial(M,Y), F is N*Y.
superfactorial(K,1) :- K=0 ; K=1.
superfactorial(K,SF) :- K>1, L is K-1, superfactorial(L,A), factorial(K,B), SF is A*B.

e.g. factorial(5, SF).

Some stuff