产生下一个质数的关系

问题描述 投票:0回答:1

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

next_prime(9, X)给出X = 11next_prime(200, X)给出X = 211

但是,next_prime(9, 13)不会提供true,因为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似乎是唯一有问题的规则。

谢谢您的帮助!

prolog primes
1个回答
0
投票

参数不正确。机构由于行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.
© www.soinside.com 2019 - 2024. All rights reserved.