有人可以帮助我找到在Prolog中获得逆阶乘的方法吗...
Can someone helping me to find a way to get the inverse factorial in Prolog...
例如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.
推荐答案Prolog的谓词是关系,因此一旦定义了阶乘,就也隐式定义了逆.但是,常规算术是在Prolog中设置的,也就是说,必须在运行时知道(is)/2或(>)/2中的整个表达式,否则,将发生错误.约束克服了这个缺点:
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.由于SICStus 4.3.4和SWI 7.1.25也终止了以下内容:
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.
更多推荐
Prolog中的逆阶乘
发布评论