Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create a List of Sieve Primes in Prolog

Status
Not open for further replies.

Samantha2323

Programmer
Apr 17, 2010
6
US
Help Please I need to create a query in prolog that will print on Sieve of Eratosthenes primes only as an example

? primes(10,L).

L = [2,3,5,7]


I need help please
thank you
 
% first build the list [1, 2, 3, ... N] using 'between',
% then eliminate all non-primes from that list

primes(N, L) :-
findall(X, between(1, N, X), FullList),
eliminate_non_primes(FullList, L).

% eliminate_non_primes(L1, L2) - does what it says

eliminate_non_primes([], []).
eliminate_non_primes([H|T], [H|T1]) :-
prime(H),!,
eliminate_non_primes(T, T1).
eliminate_non_primes([_|T], T1) :-
eliminate_non_primes(T, T1).

% prime(X) - verifies that X is prime (taken from
% % for simplicity)

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

has_factor(X, F) :-
X mod F =:= 0, !.
has_factor(X, F) :-
F * F < X,
F2 is F + 2,
has_factor(X, F2).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top