Search code examples
numbersprologclpfd

Digit sum in Prolog


How can I define in Prolog the rule to calculate the digit sum of an integer?

Example:

digitsum[Integer, Result] :- ...

so that the query digitsum(123, X). results in X = 6 (=1+2+3). A solution running under SWI-Prolog is appreciated.


Solution

  • This problem naturally leads to an implementation using library(clpfd):

    :- use_module(library(clpfd)).
    
    digitsum(Z,S) :-
       Z #= 0,
       S #= 0.
    digitsum(Z0, S0) :-
       Z0 #> 0, S0 #> 0,
       S0 #= Z0 mod 10 + S1,
       Z1 #= Z0 // 10,  % should be rather div
       digitsum(Z1, S1).
    
    ?- digitsum(D,S).
       D = S, S = 0
    ;  D = S, S in 1..9
    ;  D in 10..99, D/10#=_A, D mod 10#=_B,
       _A in 1..9, _B+_A#=S, _B in 0..9, S in 1..18
    ;  ... .
    

    The first answer is about zero. The second says that a number 1..9 is the same as its sum. Then it talks about the numbers 10..99 etc.