Prolog中的逆阶乘 [英] Inverse factorial in Prolog

查看:234
本文介绍了Prolog中的逆阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我找到在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中的逆阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆