prolog - 产生下一个素数的关系
问题描述
我正在尝试创建一个将数字与其下一个素数相关联的 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
似乎是唯一有问题的规则。
感谢您的任何帮助!
解决方案
论据不成立。研究所 你得到因为线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.
推荐阅读
- sql - 发送到客户端后无法设置标题(发布到数据库)
- asp.net - Mono + Apache + ASP.NET 中的 500 错误
- r - 多元回归Excel
- nginx - 如何删除 .php 和 .html 到 URL 并在 Nginx 中添加斜杠?
- string - 使用 bash 从包含多个单词的字符串中的每个单词中提取最后一位数字
- regex - 在 Splunk 中将一组字符转置为另一组字符
- mysql - MySQL - 每个州根据单个 export_values 的总和导出的顶级产品
- python-3.x - AttributeError:Roboclaw 实例没有属性“_port”
- ruby-on-rails - Rails 关联不适用于属性
- oracle - PostgreSQL 分页和行号索引