Prolog Find N prime numbers - prolog

I have a problem with the recursive function of Prolog. I believe I am not implementing it right and need help.
I need to generate the first N prime numbers and return it in a list. Generating the prime number is not an issue, but rather, generating it in a list is the issue I have.
This is the part of the relevant code:
genList(_, 0, _).
genList(X, N, PrimeList, PrimeList):-
N > 0,
isprime(X),
X1 is X +1,
N1 is N -1,
genList(X1,N1,[X|PrimeList], [X|PrimeList]),!.
genList(X, N, PrimeList, PrimeList):-
N>0,
\+isprime(X),
X1 is X + 1,
genList(X1,N,PrimeList, PrimeList).
This is what I type into the Prolog interpreter:
genList(1,N, [],L).
For the 1st line, how do I make the base case such that when N=0, I stop recursing? Is this correct?
As for the next 2 clauses, I am having difficulty in thinking in terms of logic programming. I definitely feel that this is not logic programming style.
I want to say that when isPrime(X) fails, we continue to the next number without saving anything, but when isPrime(X) is true, then we recurse and continue to the next number, saving X.
How do I do that in Prolog?

First of all, you shouldn't need 4 arguments to your main predicate if you only want two. Here you want the list of the first primes up to N. So an argument for N and an argument for the list should be enough:
primeList(N, L) :-
% eventually in the body a call to a worker predicate with more arguments
Now here, your logic is explained in those terms:
primeList(N, [N|L]) :-
% If we're not at the base case yet
N > 0,
% If N is a prime
isPrime(N),
NewN is N - 1,
% Let's recurse and unifie N as the head of our result list in the head
% of the predicate
primeList(NewN, L).
primeList(N, L) :-
% Same as above but no further unification in the head this time.
N > 0,
% Because N isn't a prime
\+ isPrime(N),
NewN is N - 1,
primeList(NewN, L).
To that you'd have to add the base case
primeList(0, []).
You could rewrite that with cuts as follows:
primeList(0, []) :- !.
primeList(N, [N|L]) :-
isPrime(N),
!,
NewN is N - 1,
primeList(NewN, L).
primeList(N, L) :-
NewN is N - 1,
primeList(NewN, L).

Here's what you meant to write:
genList(N, L) :- genList(2, N, L, []).
genList(X, N, L, Z):- % L-Z is the result: primes list of length N
N > 0 ->
( isprime(X) -> L=[X|T], N1 is N-1 ; L=T, N1 is N ),
X1 is X + 1,
genList(X1,N1,T,Z)
;
L = Z.
The if-then-else construct embodies the cuts. And you're right, it's essentially a functional programming style.
We can introduce a little twist to it, disallowing requests for 0 primes (there's no point to it anyway), so that we also get back the last generated prime:
genList(1, [2], 2) :- !.
genList(N, [2|L], PN) :- N>1, L=[3|_], N2 is N-2, gen_list(N2, L, [PN]).
gen_list(N, L, Z) :- L=[P|_], X is P+2, gen_list(X, N, L, Z).
gen_list(X, N, L, Z) :- % get N more odd primes into L's tail
N > 0 ->
( isprime(X) -> L=[_|T], T=[X|_], N1 is N-1 ; L=T, N1 is N ),
X1 is X + 2,
gen_list(X1,N1,T,Z)
;
L = Z. % primes list's last node
Run it:
?- genList(8,L,P).
L = [2, 3, 5, 7, 11, 13, 17, 19]
P = 19
This also enables us to stop and continue the primes generation from the point where we stopped, instead of starting over from the beginning:
?- L = [3|_], gen_list(8, L, Z), Z=[P10|_], writeln([2|L]),
gen_list(10, Z, Z2), Z2=[P20], writeln(Z).
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29|_G1037]
[29,31,37,41,43,47,53,59,61,67,71]
P10 = 29
P20 = 71

Related

Prolog: decompose number into its digits

I am studying prolog and I am faced with a problem that I cannot deal with.
Given a number, I have to check if the sum of the factorial of each digit that composes it is equal to the number itself.
Example:
145
1! + 4! + 5! = 1 + 24 + 120
Now my problem is just how to decompose the number so that I can factorial and sum each digit.
EDIT1.
thank to #slago I understand how decompose the number, but now I have a problem to sum the factorial terms:
fact(N):-
fact(N, N, _ListNumber).
fact(N, 0, ListNumber):-
factorial(ListNumber, 1, Sum),
Sum == N.
fact(N, Number, [D|R]):-
D is Number mod 10,
Number1 is Number div 10,
fact(N, Number1, R).
factorial([], Counter, Counter).
factorial([D|R], Counter, Sum):-
print([D|R]),
checksum(D, Counter),
factorial(R, Counter, Sum).
checksum(D, Counter):-
Counter1 is Counter * D,
M is D - 1,
M >= 2, !,
checksum(M, Counter1).
I have tried like this, but I noticed [D|R] results empty, and I don't understand why.
Your code is organized in a very confusing way. It is best to code independent predicates (for more specific purposes) and, after that, use them together to get the answer you want.
Start by creating a predicate to decompose a natural number into digits.
decompose(N, [N]) :- N<10, !.
decompose(N, [D|R]) :- N>=10, D is N mod 10, M is N//10, decompose(M, R).
Example of decomposition:
?- decompose(145, D).
D = [5, 4, 1].
Then, create a predicate to compute the factorial of a natural number.
fact(N, F) :- fact(N, 1, F).
fact(0, A, A) :- !.
fact(N, A, F) :- N>0, M is N-1, B is N*A, fact(M, B, F).
Example of factorial:
?- fact(5, F).
F = 120.
After that, create a predicate to map each number of a list into its corresponding factorial (alternatively, you could use the predefined predicate maplist/3).
map_fact([], []).
map_fact([X|Xs], [Y|Ys]) :- fact(X,Y), map_fact(Xs, Ys).
Example of mapping:
?- decompose(145, D), map_fact(D, F).
D = [5, 4, 1],
F = [120, 24, 1].
You must also create a predicate to compute the sum of the items of a list (alternatively, you could use the predefined predicate sum_list/2).
sum(L, S) :- sum(L, 0, S).
sum([], A, A).
sum([X|Xs], A, S) :- B is A+X, sum(Xs, B, S).
Example of summation:
?- decompose(145, D), map_fact(D, F), sum(F, S).
D = [5, 4, 1],
F = [120, 24, 1],
S = 145.
Finally, create the predicate to check the desired number property.
check(N) :- decompose(N, D), map_fact(D, F), sum(F, N).
Example:
?- check(145).
true.
?- check(146).
false.

PROLOG : Given a number X, find all multiples of 4 less or equal than X

I have the following program:
list4(N, L) :-
list4(0, N, L).
list4(N, N, [N]).
list4(N0, N, [N0| List]) :-
N0 < N,
N1 is N0+1,
list4(N1, N, List).
When i change the line N1 is N0+1 to N1 is 4*N0 i get stack limit exceeded error.
My expected result is
list4(10,L).
L = [4,8]
Two problems with the 4*N0 version:
In list4/2 you initialize list4/3 with N0=0, which, multiplied with anything, always stays 0. That causes the infinite recursion. As you want multiples of four, you can just keep increasing N0 by one in each step and multiply it by 4 before putting it into the list.
The anchor relies on your count variable arriving at N exactly, but N0 * 4 overshoots. The first rule of list4/3 has to cover the rest of the cases with N0*4 > N as well. To also include the upper limit in the result, we can make the anchor stop at values larger than the limit and handle the upper bound itself in the second rule.
Expressed in code:
list4(N, L) :-
list4(1, N, L).
list4(N0, N, []) :- N4Times is N0*4,N4Times > N.
list4(N0, N, [N4Times| List]) :-
N4Times is N0*4,
N4Times =< N,
N1 is N0 + 1,
list4(N1, N, List).
Results in:
?- list4(10,L).
L = [4, 8] ;
false.
?- list4(8,L).
L = [4, 8] ;
false.
You can initialize the accumulator with 0 and increment it by 4 at each step.
% list4(+Upperbound, -MultiplesOfFour)
list4(U, M) :-
list4(0, U, M).
list4(A, U, L) :-
M is A+4,
( M =< U
-> L = [M|Ms],
list4(M, U, Ms)
; L = [] ).
Examples:
?- list4(10, L).
L = [4, 8].
?- list4(8, L).
L = [4, 8].
?- list4(20, L).
L = [4, 8, 12, 16, 20].
?- list4(30, L).
L = [4, 8, 12, 16, 20, 24, 28].
?- list4(3, L).
L = [].

How do I create a list with elements from 1 to N in prolog

I've tried to create a program that makes a list with elements from 1 to N.
increasing(L, N):-
increasing(L, N, 1).
increasing([X|L], N, X):-
X =< N,
X1 is X + 1,
increasing(L, N, X1).
But for some reason it doesn't work
The problem is that eventually, you will make a call to increasing/3 where X <= N is not satisfied, and then that predicate will fail, and thus "unwind" the entire call stack.
You thus need to make a predicate that will succeed if X > N, for example:
increasing(L, N):-
increasing(L, N, 1).
increasing([], N, X) :-
X > N,
!.
increasing([X|L], N, X):-
X =< N,
X1 is X + 1,
increasing(L, N, X1).
For example:
?- increasing(L, 5).
L = [1, 2, 3, 4, 5].

Separating a list into a list of fixed length sublists

Given a list L, for instance, [1,2,3,4,5,6,7] and a number N, for instance 3, I would like to make a predicate that would separate the elements of L into lists of size N.
So, the result will be: [[1,2,3], [4,5,6], [7]] in our case.
What I have tried:
% List containing the first N elements of given list.
takeN([X|Xs], 0, []) :- !.
takeN([X|Xs], N, [X|Ys]) :- N1 is N-1, takeN(Xs, N1, Ys).
% Given list without the first N elements.
dropN(R, 0, R) :- !.
dropN([X|Xs], N, R) :- N1 is N-1, dropN(Xs, N1, R).
% size of list.
sizeL([], 0) :- !.
sizeL([X|Xs], N) :- sizeL(Xs, N1), N is N1+1.
blockify(R, N, [R|[]]) :- sizeL(R, N1), N1 < N, !.
blockify([X|Xs], N, [Y|Ys]) :- sizeL(R, N1), N1 >= N, takeN([X|Xs], N, Y),
dropN([X|Xs], N, Res), blockify(Res, N, Ys).
It doesn't work (blockify([1,2,3], 2, R) for example returns false, instead of [[1,2], [3]]).
I can't find where I'm mistaken, though. What's wrong with this?
I think you are making thinks a bit overcomplicated. First of all let's exclude the case where we want to blockify/3 the empty list:
blockify([],_,[]).
Now in the case there are elements in the original list, we simply make use of two accumulators:
- some kind of difference list that stores the running sequence; and
- an accumulator that counts down and look whether we reached zero, in which case we append the running difference list and construct a new one.
So this would be something like:
blockify([H|T],N,R) :-
N1 is N-1,
blockify(T,N1,N1,[H|D],D,R).
Now the blockify/5 has some important cases:
we reach the end of the list: in that case we close the difference list and append it to the running R:
blockify([],_,_,D,[],[D]).
we reach the bottom of the current counter, we add the difference list to R and we intialize a new difference list with an updated counter:
blockify([H|T],N,0,D,[],[D|TR]) :-
blockify(T,N,N,[H|D2],D2,TR).
none of these cases, we simply append the element to the running difference decrement the accumulator and continue:
blockify([H|T],N,M,D,[H|D2],TR) :-
M > 0,
M1 is M-1,
blockify(T,N,M1,D,D2,TR).
Or putting it all together:
blockify([],_,[]).
blockify([H|T],N,R) :-
N1 is N-1,
blockify(T,N1,N1,[H|D],D,R).
blockify([],_,_,D,[],[D]).
blockify([H|T],N,0,D,[],[D|TR]) :-
blockify(T,N,N,[H|D2],D2,TR).
blockify([H|T],N,M,D,[H|D2],TR) :-
M > 0,
M1 is M-1,
blockify(T,N,M1,D,D2,TR).
Since in each recursive call all clauses run in O(1) and we do the recursion O(n) deep with n the number of elements in the original list, this program runs in O(n).
if your Prolog provides length/2, a compact solution could be:
blockify(R, N, [B|Bs]) :-
length(B, N),
append(B, T, R),
!, blockify(T, N, Bs).
blockify(R, _N, [R]).
Let me teach you how to debug a Prolog query:
1) blockify([1,2,3], 2, R)
2) does it match blockify(R, N, [R|[]]) ? oh yes,
it can be bound to blockify([1, 2, 3], 2, [[1, 2, 3]])
3) let's evaluate the body: sizeL(R, N1), N1 < N, !.
Replace R and N, we get: sizeL([1, 2, 3], N1), N1 < 2, !.
4) evaluate sizeL([1, 2, 3], N1): for brevity, since it's a common
list count predicate, the result should be obvious: N1 = 3
5) evaluate N1 < N: 3 < 2 => false
6) since the rest are all , (and operator) a single false
is enough to make the whole body to evaluate to false
7) there you go, the predicate is false
See where your mistake is?

collatz-list implementation using Prolog

I am trying to create a function called collatz_list in Prolog. This function takes two arguments, the first one is a number and the second in a list. This list will be my output of this function. So, here's my function:
collatz_list(1,[1]).
collatz_list(N,[H|T]) :-
N > 1,
N mod 2 =:= 0,
collatz_list(N, [H|T]).
collatz_list(N,[H|T]) :-
N > 1,
N mod 2 =:= 1,
N is N*3 +1,
collatz_list(N,[H|T]).
I am struggling with creating the output list. Can anyone help me on that?
Thanks.
Assuming you want to write a collatz_list/2 predicate with parameters (int, list), where list is the collatz sequence starting with int and eventually ending with 1 (we hope so! It's an open problem so far); you just have to code the recursive definition in the declarative way.
Here's my attempt:
/* if N = 1, we just stop */
collatz_list(1, []).
/* case 1: N even
we place N / 2 in the head of the list
the tail is the collatz sequence starting from N / 2 */
collatz_list(N, [H|T]) :-
0 is N mod 2,
H is N / 2,
collatz_list(H, T), !.
/* case 2: N is odd
we place 3N + 1 in the head of the list
the tail is the collatz sequence starting from 3N + 1 */
collatz_list(N, [H|T]) :-
H is 3 * N + 1,
collatz_list(H, T).
Modified version, includes starting number
Let's test it:
full_list(N, [N|T]) :-
collatz_list(N, T).
collatz_list(1, []).
collatz_list(N, [H|T]) :-
0 is N mod 2,
H is N / 2,
collatz_list(H, T), !.
collatz_list(N, [H|T]) :-
H is 3 * N + 1,
collatz_list(H, T).
?- full_list(27, L).
L = [27, 82, 41, 124, 62, 31, 94, 47, 142|...].
First, we define the simple auxiliary predicate collatz_next/2 to performs a single Collatz step:
collatz_next(X,Y) :-
X >= 1,
( X =:= 1 -> Y = 1
; X mod 2 =:= 0 -> Y is X // 2
; Y is 3*X + 1
).
To advance to a fixed point,
we use the meta-predicates fixedpoint/3 and fixedpointlist/3:
?- fixedpoint(collatz_next,11,X).
X = 1. % succeeds deterministically
?- fixedpointlist(collatz_next,11,Xs).
Xs = [11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]. % succeeds deterministically
Both meta-predicates used in above query are based on the monotone control construct if_/3 and the reified term equality predicate (=)/3, and can be defined as follows:
:- meta_predicate fixedpoint(2,?,?).
fixedpoint(P_2, X0,X) :-
call(P_2, X0,X1),
if_(X0=X1, X=X0, fixedpoint(P_2, X1,X)).
:- meta_predicate fixedpointlist(2,?,?).
fixedpointlist(P_2,X0,[X0|Xs]) :-
call(P_2, X0,X1),
if_(X0=X1, Xs=[], fixedpointlist(P_2,X1,Xs)).

Resources