我正在尝试理解练习的解决方案,以便准备我的逻辑编程考试,并且我无法理解下面代码的逻辑。
问题中的解释:
n 是素数 n > 1和1< m < 名词的 n / m 具有非零余数。
以下是代码:
isPrime(X) :- help(X,X).
help(X,Y) :-
Y > 2,
LOW is Y-1,
Z is X mod LOW,
Z > 0,
help(X,LOW).
help(X,2).
有人可以帮我解释一下代码。
答案 0 :(得分:2)
此代码尝试通过执行以下操作来确定X是否为素数:
let Y = X initially
1. Check to see if the number (Y) is greater than 2.
2. Assign a new variable (LOW) one-less than the starting number (Y-1)
3. If X mod LOW is greater than zero, then recurse with LOW as the new Y
重复此操作,直到X mod LOW大于零且你的mod为1(Y = 2),然后如果我正确读取(并记住公式),你应该把X作为素数。< / p>
If at some point X mod LOW equals zero, then X is a non-prime.
Example: X=6 (non-prime)
Y=6, LOW=5, Z = 6 mod 5 = 1 --> help(6,5)
Y=5, LOW=4, Z = 6 mod 4 = 2 --> help(6,4)
Y=4, LOW=3 Z = 6 mod 3 = 0 --> non prime because it's divisible by 3 in this case
Example: X=5 (prime)
Y=5, LOW=4, Z= 5 mod 4 = 1 --> help(5,4)
Y=4, LOW=3, Z= 5 mod 3 = 2 --> help(5,3)
Y=3, LOW=2 Z= 5 mod 2 = 3 --> help(5,2)
Y=2, --> once you get to this point, X is prime, because LOW=1,
and any number mod 1 is greater than zero, and you can't "X mod 0".
有意义吗?它有效地迭代小于X的数字,看它是否平均分配(mod = 0)。
答案 1 :(得分:0)
行。素数的定义:
如果满足以下条件,则整数 n 为素数:
- N大于1,
- N只能被自己整除1。
由于每个整数都是(A)可被自身整除,并且(B)可被1整除,因此没有必要检查这些条件是否成立。必须检查的真正约束是:
要使数字 n 成为素数,必须满足以下约束:
- n 必须大于1,
- 域1中必须存在 m &gt; m &lt; n , n 可被 m
整除
您的help/2
谓词通过将第二个参数与测试值一起播种并递减它来强制执行第二个约束,查找 m 来划分 n
更简单的方法可能是以声明式方式编写测试并让Prolog为您解决:
is_prime(2). % 2 is prime by definition.
is_prime(N) :- % otherwise, N is prime if,
N > 2 , % - N is greater than 2, and
0 =\= N mod 2 % - and N is odd (no real need to check even numbers, eh?
not_divisible(3,N) % - and N is not divisible any other odd number in the range 3 -- (N-1)
.
not_divisible(N,N) . % if we've counted up to N, we're good.
not_divisible(M,N) :- % otherwise...
M < N , % - if M is less than N, and
0 =:= N mod M % - and N is not divisible by M, then
M1 is M-1 , % - decrement M, and
not_divisible(M1,N) % - recurse down on the newly decremented M
. %