Home > Enterprise >  How can I find all the valid divisors (AKA A%B == 0) of a number?
How can I find all the valid divisors (AKA A%B == 0) of a number?

Time:03-28

I am writing a method modded, which is defined as modded(X,Y,Z). X is a generated list composed of the numbers in a given list Z that Y % Z == 0.

An example would be for (X,8,[2,4,5,1]) to return X = [2,4]. It does not include non mod zero numbers.

I am currently having defining my cases. My idea for the base case is defined in the example, but the recursive case should go through the list Z and compare its contents to Y, adding it to X if it is true (Y % Z == 0)

modded([],Y,Z):-     % Base case should be: Z is empty which makes X empty
    % Y > Z - 1.
    Z =:= [],
    X =:= Z.

modded([Y|T],Y,Z):-    % Recursive is Y > 1
    0 is Y mod Z,
    Y =< Z - 1,
    Zz is Y 1,
    modded(T,Zz,Z).
    % Need to check if current mods number to 0

CodePudding user response:

A simple solution could be:

modded([],_,[]).
modded([Ai|T],Mod,[Ai|Ti]):-
    0 is Mod mod Ai, !,
    modded(T,Mod,Ti).
modded(L,Mod,[Ai|Ti]):-
    X is Ai mod Mod,
    X \= 0,
    modded(L,Mod,Ti).

?- modded(X,8,[2,4,5,1]).
X = [2, 4, 1];
false

CodePudding user response:

You can use foldl:

checkMod(Div, ListElement, Ittr, Result) :-
    ((Div mod ListElement) =:= 0 ->  
        append(Ittr, [ListElement], Result) ;
        Result = Ittr
    ).

modded(List, Div, Result) :-
    foldl(checkMod(Div), List, [], Result).

This gives: modded([2,4,5,1], 8, Result)

Result = [2, 4, 1]

  • Related