prologfailure-sliceprogram-slicing

Prolog - get the factors for a given number doesn't stop?


I need to find the factors of a given number , e.g :

?- divisors2(40,R).
R = [40,20,10,8,5,4,2,1].

The code :

% get all the numbers between 1-X 
range(I,I,[I]).
range(I,K,[I|L]) :- I < K, I1 is I + 1, range(I1,K,L).
% calc the modulo of each element with the given number :
% any x%y=0 would be considered as part of the answer 
divisors1([],[],_).
divisors1([H|T],S,X):-divisors1(T,W,X),Z is X mod H,Z==0,S=[H|W].
divisors1([_|T],S,X):-divisors1(T,S,X).
divisors2(X,Result) :-range(1,X,Result1),divisors1(Result1,Result,X).

But when I run divisors2(40,RR). I get infinite loop and nothing is presented to the screen.

Why ?

Regards


Solution

  • You have a bug here

    divisors1([H|T],S,X):-
       divisors1(T,W,X),
       Z is X mod H,
       Z==0,S=[H|W]. <=== here
    

    If Z is Zero then S = [H|W] else S = W.