I'm new to Prolog and I need to create a list of prime numbers for a given range. Example
?- p_list(3,23,X).
X = [3, 5, 7, 11, 13, 17, 19, 23].
I got it done. I'll post the answer in case someone else needs it.
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).
prime_list(A,B,L) :-
A1 is (A // 2) * 2 + 1,
p_list(A1,B,L).
p_list(A,B,[]) :- A > B, !.
p_list(A,B,[A|L]) :-
is_prime(A), !,
next(A,A1),
p_list(A1,B,L).
p_list(A,B,L) :-
next(A,A1),
p_list(A1,B,L).
next(2,3) :- !.
next(A,A1) :- A1 is A + 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With