3

I have an easy task, but somehow I haven't solved it in over an hour. This recursion I am doing isn't working, I'm stuck in an infinte loop. It should compare the last digit of a number with every other and remember the biggest one. Would really like to know why is my logic faulty and how to solve this problem.

This is my try on it:

maxDigit(X,X):-
   X<10.
maxDigit(X,N):-
   X1 is X//10,
   X2 is X mod 10,
   maxDigit(X1,N1),
   X2=<N1,
   N is  N1.
maxDigit(X,N):-
   X1 is X//10,
   X2 is X mod 10,
   maxDigit(X1,N1),
   X2>N1,
   N is X2.
false
  • 10,264
  • 13
  • 101
  • 209
milosponj
  • 118
  • 7
  • 1
    Please add a description in your question body of what you are trying to achive. Question title can be improved as well to something like: "Find biggest digit in a number" – Alex Jun 13 '16 at 00:25
  • I fixed your question, but I won't be always your back. Next time follow what @Alex said. – peterh Jun 13 '16 at 02:45
  • Thanks, I've added more description. – milosponj Jun 13 '16 at 09:37

4 Answers4

2

Using SICStus Prolog 4.3.3 we simply combine n_base_digits/3 and maximum/2 like so:

?- n_base_digits(12390238464, 10, _Digits), maximum(Max, _Digits).
Max = 9.
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
2

A comment suggested stopping as soon as the maximum digit is encountered. This is how we do:

:- use_module(library(clpfd)).    
:- use_module(library(reif)).

#=(X, Y, T) :- X #= Y #<==> B, bool10_t(B, T).

bool10_t(1, true).
bool10_t(0,false).

Based on if_/3, (;)/3 and (#=)/3 we then define:

n_base_maxdigit(N, Base, D) :-
   N    #>  0,                               % positive integers only
   Base #>  1,                               % smallest base = 2
   D    #>= 0,
   D    #<  Base,
   n_base_maxdigit0_maxdigit(N, Base, 0, D).

n_base_maxdigit0_maxdigit(N, Base, D0, D) :-
   D1 #= N mod Base,
   N0 #= N //  Base,
   D2 #= max(D0,D1),
   if_(( D2 + 1 #= Base ; N0 #= 0 ),
       D = D2,
       n_base_maxdigit0_maxdigit(N0, Base, D2, D)).

Sample query using SWI-Prolog 7.3.22 with Prolog :

?- use_module(library(lambda)).
true.

?- Max+\ ( N is 7^7^7 * 10+9, time(n_base_maxdigit(N,10,Max)) ).
% 663 inferences, 0.001 CPU in 0.001 seconds (100% CPU, 1022162 Lips)
Max = 9.
repeat
  • 18,496
  • 4
  • 54
  • 166
1

You have just to use if/then/else :

maxDigit(X,X):-
   X<10,
   !. % added after false's remark

maxDigit(X,N):-
   X1 is X//10,
   X2 is X mod 10,
   maxDigit(X1,N1),
   (   X2<N1
   ->  N =  N1
   ;   N = X2).
joel76
  • 5,565
  • 1
  • 18
  • 22
0

in SWI-Prolog could be:

maxDigit(N,M) :- number_codes(N,L), max_list(L,T), M is T-0'0.
CapelliC
  • 59,646
  • 5
  • 47
  • 90
  • Alright! How about using `max_member(T,L)` instead of `max_list(L,T)` and adding `:- use_module(library(lists)).` ? That way the same code would run with SWI *and* SICStus. – repeat Jun 14 '16 at 09:52