4
votes

How can I print just even numbers in Prolog? This is my code to print numbers from 3 to 1: And how using mult without (*) in anthor example:

predicates
    count(integer).
clauses
    count(1) :- write(1), nl, !.
    count(X) :- X > 1, write(X), nl, X1 = X-1, count(X1), !.
2
If you want to print even number, this X>1,write(X) is pretty wrong. It will print any number that is greater than X,that including 3 - Shevliaskovic

2 Answers

1
votes

How can I print just even numbers in Prolog

?- between(1, 3, X), X mod 2 =:= 0.
X = 2.
1
votes

ДМИТРИЙ МАЛИКОВ did a nice, concise method. The one below just builds on the approach that was started:

predicates
    count(integer).

clauses
    count(X) :-
        X /\ 1 =:= 1, !,  % Using bitwise AND (/\) to check for odd
        X1 is X - 1,
        count(X1).
    count(X) :-
        X > 1,
        write(X), nl,
        X1 is X - 2,
        count(X1).

| ?- count_even(7).
6
4
2

I used bitwise AND (/\) to check the parity of the number just to illustrate a different method. The mod operator works just as well.

Note that for arithmetic expression assignment in prolog, you need is, not =. is will calculate the expression on the right and unify the result to the uninstantiated variable on the left. = will not evaluate the expression.