序言中的哥德巴赫猜想 [英] Goldbach’s Conjecture in prolog

查看:74
本文介绍了序言中的哥德巴赫猜想的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哥德巴赫猜想:每个大于 2 的正偶数都是两个素数之和.例如 28 (5,23 和 11,17)

Goldbach’s Conjecture : Every positive even number greater than 2 is the sum of two prime numbers. Eg 28 (5,23 and 11,17)

我希望 Prolog 代码打印在下面(所有组合):

I want Prolog code to print below (all combinations) :

?- goldbach(28, L). 

Output :

L = [5,23];
L = [11, 17];

我有一个代码可以打印单个组合[5,23],但不能打印下一个[11,17].

I have a code which prints single combination[5,23], but not the next [11,17].

is_prime(2).
is_prime(3).
is_prime(P) :- integer(P), P > 3, P mod 2 =\= 0, \+ has_factor(P,3).  

has_factor(N,L) :- N mod L =:= 0.
has_factor(N,L) :- L * L < N, L2 is L + 2, has_factor(N,L2).

goldbach(4,[2,2]) :- !.
goldbach(N,L) :- N mod 2 =:= 0, N > 4, goldbach(N,L,3).

goldbach(N,[P,Q],P) :- Q is N - P, is_prime(Q), !.
goldbach(N,L,P) :- P < N, next_prime(P,P1), goldbach(N,L,P1).

next_prime(P,P1) :- P1 is P + 2, is_prime(P1), !.
next_prime(P,P1) :- P2 is P + 2, next_prime(P2,P1).

推荐答案

删除剪切(并添加条件以避免重复答案).

Drop the cuts (and add a condition to avoid duplicate answers).

goldbach(4,[2,2]).
goldbach(N,L) :-
  N mod 2 =:= 0,
  N > 4,
  goldbach(N,L,3).
goldbach(N,[P,Q],P) :-
  Q is N - P,
  is_prime(Q), P < Q.
goldbach(N,L,P) :-
  P < N,
  next_prime(P,P1),
  goldbach(N,L,P1).

这篇关于序言中的哥德巴赫猜想的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆