见http://www.swi-prolog.org/pldoc/man?function=mod/2:
+IntExpr1 mod +IntExpr2
取模,定义为 Result = IntExpr1 - (IntExpr1 div IntExpr2) × IntExpr2,其中 div 为取整除法。
所以R 应该是0。 mod 只有一个结果。
一个可行的解决方案是:
primeNumber(A) :-
A > 1, % Negative numbers, 0 and 1 are not prime.
prime_prime(A, 2). % Begin iteration:
prime_prime(A, B) :- % Test if A divides by B without remainder
B >= A % The limit was reached?
-> true % Then it's prime.
; 0 is A mod B % B divides A without a remainder?
-> false % Then it's not prime.
; succ(B, C), % Otherwise: C is B + 1
prime_prime(A, C). % Test if C divides A.
顺便说一句,primeNumber/1(名为primeNumber 的谓词,带有一个参数)是与primeNumber/2(同名,两个参数)完全不同的谓词。仅获得起始值的额外参数的“子函数”通常具有相同的名称。所以你应该使用primeNumber而不是prime_prime,尽管在Prolog中你通常不使用camelCase。
使用 Sergei Lodyagin 在 cmets 中提出的优化:
primeNumber(A) :-
A > 1, % Negative numbers, 0 and 1 are not prime.
sqrt(A, L), % A prime factor of A is =< the square root of A.
prime_prime(A, 2, L). % Begin iteration:
prime_prime(A, B, L) :- % Test if A divides by B without remainder
B >= L % The limit was reached?
-> true % Then it's prime.
; 0 is A mod B % B divides A without a remainder?
-> false % Then it's not prime.
; succ(B, C), % Otherwise: C is B + 1
prime_prime(A, C, L). % Test if C divides A.
如果你使用预定义谓词between(+Low, +High, ?Value):
primeNumber(A) :-
L is floor(sqrt(A)),
\+ (between(2, L, X),
0 is A mod X).
为了进一步减少迭代次数,您只需要测试奇数模块:
primeNumber(2).
primeNumber(A) :-
A > 2,
\+ 0 is A mod 2,
L is floor(sqrt(A) / 2),
\+ (between(1, L, X),
0 is A mod (1 + 2*X)).