Search code examples
prolog

number of digits in integer number using prolog


can someone help me with this problem ?

SWISH image of code

numofdig(A,B):-
   A>0,
   A is (A//10),
   succ(0,S),
   numofdig(A),
   B is S,
   write(B).

this is my code and its not working .


Solution

  • I'd do this:

    number_of_digits( M , N ) :-
      integer(M),              % is it an integer?
      V is abs(M),             % sign is irrelevant as to number of digits
      number_of_digits(V,1,N). % invoke the helper predicate with the accumulator seeded with 1 (all numbers have at least one digit).
    
    number_of_digits( M , T , N ) :-
        M > 9,                        % Is the value > 9?
        !,                            %   If so, eliminate the choice point (it's not going to stop being 10+ on backtracking)
        T1 is T+1 ,                   %   Increment the accumulator
        M1 is M // 10 ,               %   drop the rightmost digit via integer division by 10
        number_of_digits(M1,T1,N)     %   and recurse down on what's left.
        .                             % Otherwise (the value is 0-9)
    number_of_digits( _ , N , N ) .   %   The accumulator has the result.