Search code examples
prologclpfdinteger-arithmetic

prolog how to use math operation


I am a novice in prolog programming, i use swi-prolog. Now I'm stucked by some math problems

as we know the predicate :A is 3+3.works well,the answer is A=6.

but if I want to find two digits (A and B) from 0~9 that a+b=6 6 is A+B does't work. so I want to know if there is a easy way to do this? And what if I want to find 3 digits (A,B and C)from 0~9 that A+B+C=13 how to do this ?


Solution

  • the simpler way, working in every Prolog implementation: declare a predicate digit/1 (the notation predicate/N means that predicate has N arguments)

    digit(D) :- member(D, [0,1,2,3,4,5,6,7,8,9]).
    

    then you can ask

    ?- digit(A),digit(B),6 is A+B.
    A = 0,
    B = 6 ;
    A = 1,
    B = 5 ;
    ...
    

    since sum is symmetric, maybe you want to reduce the duplicate solution with

    ?- digit(A),digit(B),A=<B,6 is A+B.
    

    Using library(clpfd) you can avoid defining your digit/1 predicate, and gain a lot of functionality:

    ?- [library(clpfd)].
    true.
    
    ?- [A,B,C] ins 0..9, A+B+C #= 13, label([A,B,C]).
    A = 0,
    B = 4,
    C = 9 ;
    A = 0,
    B = 5,
    C = 8 
    ...
    

    note that now the incognite can stay to the left of the 'assignment'...