Search code examples
listprologclpfd

PROLOG Print numbers that end in 7 and the sum of its digits is greater than 100


I need to make a predicate that receives a numeric list and print only the numbers that end in 7 and that the sum of its digits is greater than 100

I made the predicates for separated but I need help making a union of the two predicates, I mean that the two predicates go into one only predicate, this is what I did so far:

%sum of digits greater than 100
 multi(X):-
0 is X mod 100
sum([],0).
sum([P|Q],Z).
multi(P), sum(Q,Z1), Z is P + Z1.
sum([P|Q],Z).
not multi(P), sum(Q,Z).

%print the numbers that end in 7
end(Y):-
7 is Y mod 10.
listend([],0).
listend([P|Q]):-
end(P),write(P), nl, listend(Q).
listend([P|Q]):-
not(end(P)), listend(Q).

Solution

  • This works for me:

    ?- filter([147, 24, 57, 17, 3667], X), write(X), nl, fail.
    
    sumdigits(0, 0).
    sumdigits(X, Z) :-
        X > 0,
        Z1 is X mod 10, 
        X2 is X // 10,
        sumdigits(X2, Z2), 
        Z is Z1 + Z2.
    
    filter([], []).
    filter([H|X], [H|Y]) :-
        sumdigits(H, D),
        D > 10,
        7 is H mod 10, !,
        filter(X, Y).
    filter([_|X], Y) :- filter(X, Y).
    

    I get:

    [147, 57, 3667]
    No.
    

    I assumed you meant that the sum of the digits was greater than 10, rather than 100.