[英]Basic primality test predicate in Prolog
I am trying to create a predicate isPrime/1
that checks if a given number is prime or not.我正在尝试创建一个谓词
isPrime/1
来检查给定数字是否为素数。 I have come up with the following code:我想出了以下代码:
primeRec(_, 2).
primeRec(X, Y) :- Y > 2, X mod Y-1 > 0, primeRec(X, Y-1).
isPrime(2).
isPrime(X) :- X > 1, X mod 2 > 0, primeRec(X, X).
but it does not seem to work, and I have no idea why.但它似乎不起作用,我不知道为什么。 I've found my code to follow the same idea as this one here , except that mine always returns
false.
我发现我的代码遵循与此处代码相同的想法,只是我的代码始终返回
false.
for any ?- isPrime(X).
对于任何
?- isPrime(X).
with X bigger than 2, which obviously should not happen. X 大于 2,这显然不应该发生。
The problem is that you need to define another variable, say Y1
, and unify it with the evaluation of Y-1
, ie, Y1 is Y - 1
and use Y1
instead of Y-1
in the second rule for primeRec/1.
问题是您需要定义另一个变量,例如
Y1
,并将其与Y-1
的评估统一,即Y1 is Y - 1
并在primeRec/1.
的第二条规则中使用Y1
而不是Y-1
1。 This because if you want to evaluate an arithmetic expression you need to use is
.这是因为如果你想计算一个算术表达式,你需要使用
is
。
primeRec(X, Y) :- Y > 2, Y1 is Y - 1, X mod Y1 > 0, primeRec(X, Y1).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.