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

后端 未结 3 537
南方客
南方客 2021-01-13 16:21

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 t         


        
3条回答
  •  深忆病人
    2021-01-13 16:57

    If you correct your range (use a cut for the end-of-recursion clause), you will get it sort of working. You do not immediately succeed upon finding all divisors though.

    A solution using your general idea, but also built-ins between/3 and bagof/3 (to make typing a bit easier):

    divisors(X, Divs) :- bagof(D, divs(X,D), Divs).
    divs(X,D) :- between(1,X,D), 0 is X mod D.
    

    Please note that this solution returns the divisors in increasing order.

提交回复
热议问题