Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

?- goldbach(28, L). 

Output :

L = [5,23];
L = [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).
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
171 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...