man zet
man zet

Reputation: 901

List of Prime Numbers. Why is my code not working?

I'm new to prolog an I try to implement a function that gives me a list of primes in an specific range (from A to B). Here is my code:

%ending recursion
prime_list(A,A,[A]) :- is_prime(A).
prime_list(A,A,[]) :- not(is_prime(A)).

% if A is prime:
prime_list(A,B,[H|T]) :-
   N1 is A+1,  H is A, is_prime(A), prime_list(N1,B,T).

% if A is not prime:
prime_list(A,B,[H|T]) :-
   N1 is A+1, not(is_prime(A)), prime_list(N1,B,[H|T]).

as long as B is smaler then 9 it works. So for example

prime_list(1,8,X).

gives me

X = [2, 3, 5, 7]

but for B bigger than 8 Prolog doesn't terminate and seems to be stuck in an endless loop. Can someone explain me why my approach is not working?

I'm pretty sure that my "is_prime" -function works, because I've tested it with many values. But to be on the safe side, I'll put it here too:

is_prime_help(X,I) :-
  (not(I is 1), 0 is mod(X,I));
  (not(I is 1), N1 is I-1, is_prime_help(X, N1)).

is_prime(X) :- not(X is 1), N1 is X-1, not(is_prime_help(X,N1)).

Upvotes: 0

Views: 64

Answers (1)

jnmonette
jnmonette

Reputation: 1794

In the last clause, you should replace both [H|T] by just T. Otherwise, this assumes that at least a prime must come after. So what you would hope to be the last recursive call looks like prime_list(9,9,[H|T]) and the two first clauses never match and it never ends...

Upvotes: 1

Related Questions