首页 > 解决方案 > 产生下一个素数的关系

问题描述

我正在尝试创建一个将数字与其下一个素数相关联的 Prolog 规则。我有它,以便它可以在数字之后生成下一个素数,但它无法找到素数直接跟随的数字。例如,以下是预期的:

next_prime(9, X)X = 11.
next_prime(200, X)X = 211.

然而,next_prime(9, 13)givestrue不是预期的,因为 13 不是 9 之后的下一个素数,因为 11 是。

此外,该规则不能反向工作:
next_prime(X, 13).给出

Arguments are not sufficiently instantiated
In:
   [2] 13 is _1410+1
   [1] next_prime(_1466,13) at line 22

我不明白这个错误信息是什么意思。

这是我的代码:

divisible_over(A, B) :-
    0 =:= A mod B,
    !.
divisible_over(A, B) :-
    A > B + 1,
    divisible_over(A, B + 1).

composite(A) :-
    divisible_over(A, 2).

prime(A) :-
    not(composite(A)).

next_prime(A, P) :-
    P is A + 1,
    prime(P),
    !.
next_prime(A, P) :-
    A0 is A + 1,
    next_prime(A0, P).

prime工作正常。next_prime似乎是唯一有问题的规则。

感谢您的任何帮助!

标签: prologprimes

解决方案


论据不成立。研究所 你得到因为线P是A + 1。如果你问 Prolog next_prie(X,13)。这条线的计算结果是 13 是 X+1。Prolog 不知道在这种情况下该怎么做,因为 X 还没有值 -> 这会导致错误

我会这样做:

% prolog just uses this if A and P are already numbers and checks then if there are no primes between the numbers
next_prime(A,P) :-
  number(A),
  number(P),!,
  no_prime_between(A,P).

next_prime(A, P) :-
    var(P), % this line checks if P is a variable
    P is A + 1,
    prime(P),!.

next_prime(A, P) :-
    var(P), % this line checks if P is a variable
    A0 is A + 1,
    next_prime(A0, P).

% this is used so your funciton works in both direction
next_prime(A, P) :-
    var(A), % this line checks if A is a variable
    A is P - 1,
    prime(A),!.

next_prime(A, P) :-
    var(A), % this line checks if A is a variable
    P0 is P - 1,
    next_prime(A, P0).

% a new methode I introduced, that checks if there is a prime between X, and X0.
no_prime_between(X,X0) :-
  X0 is X+1.
no_prime_between(X,_) :-
  X0 is X+1,
  prime(X0), !, false.
no_prime_between(X,Y) :-
  X0 is X+1,
  no_prime_between(X0,Y).

这导致以下输出:

?- next_prime(9,X).
X = 11 .

?- next_prime(X,11).
X = 7.

?- next_prime(9,11).
true .

?- next_prime(9,13).
false.


推荐阅读