I trying to write a function – noPrime(X,Result) which gives a list of all the non-primary number in range [X-1,2] .
For example –
noPrime(9,Result).
Result = [8,6,4]
So far I tried the follow –
nprimes(4,[]) :- !.
nprimes(X,[H|Rest]) :- H is X-1,nprimes(H,NewRest),
( isPrime(H) -> Rest = NewRest; Rest = [H|NewRest]).
But it gives –
Result = [8, 8, 7, 6, 6, 5, 4, 4].
Seems like it duplicate the non-primary and gives one time the primary .
isPrime – is my own function which works well .
Can you detect what is the wrong here and how to correct it ?
You are always adding the element at the head of the second argument of
nprimes/2.Then, if the element is prime the second argument will still have the element; and if the element was not prime it will be added twice.
It should read: