Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse factorial in Prolog

Can someone helping me to find a way to get the inverse factorial in Prolog...

For example inverse_factorial(6,X) ===> X = 3.

I have been working on it a lot of time.

I currently have the factorial, but i have to make it reversible. Please help me.

like image 353
sonchi Avatar asked Sep 26 '13 10:09

sonchi


1 Answers

Prolog's predicates are relations, so once you have defined factorial, you have implicitly defined the inverse too. However, regular arithmetics is moded in Prolog, that is, the entire expression in (is)/2 or (>)/2 has to be known at runtime, and if it is not, an error occurs. Constraints overcome this shortcoming:

:- use_module(library(clpfd)).

n_factorial(0, 1).
n_factorial(N, F) :-
   N #> 0, N1 #= N - 1, F #= N * F1,
   n_factorial(N1, F1).

This definition now works in both directions.

?- n_factorial(N,6).
N = 3 ;
false.

?- n_factorial(3,F).
F = 6 ;
false.

Since SICStus 4.3.4 and SWI 7.1.25 also the following terminates:

?- n_factorial(N,N).
   N = 1
;  N = 2
;  false.

See the manual for more.

like image 151
false Avatar answered Nov 30 '22 07:11

false