Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prime numbers list for a given range prolog

Tags:

primes

prolog

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].
like image 343
user1704850 Avatar asked Jan 16 '23 06:01

user1704850


1 Answers

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.
like image 95
user1704850 Avatar answered Jan 22 '23 09:01

user1704850