LCM of list PROLOG

637 Views Asked by At

How to get the LCM of a list in Prolog? Lets say the list is: [1,2,3,4,5] and the LCM will be 60. I have the following code fo the GCD and the LCM that work for 2 numbers but dont know how to apply to lists.

gcd(X, 0, X) :- !.
gcd(X, Y, Z) :-
    H is X rem Y,
    gcd(Y, H, Z).
lcm(X,Y,LCM):-
    gcd(X,Y,GCD),
    LCM is X*Y//GCD.
1

There are 1 best solutions below

0
chansey On
gcd_of_list([], 0) :- !.
gcd_of_list([X|Xs], GCD) :- gcd_of_list(Xs, GCD2), gcd(X, GCD2, GCD). 

?- gcd_of_list([150,1000,120], GCD).
GCD = 10.
lcm_of_list([],1) :- !.
lcm_of_list([X|Xs],LCM) :- lcm_of_list(Xs,LCM2), lcm(X,LCM2,LCM).

?- lcm_of_list([9, 7, 10, 9, 7, 8, 5, 10, 1],LCM).
LCM = 2520.

BTW, an interesting result is that you cannot use gcd_of_list to compute lcm_of_list directly, for example:

%% A wrong attempt 
lcm_of_list(Lst, LCM) :-
  gcd_of_list(Lst, GCD),
  mul_list(Lst, Mul),
  LCM is Mul // GCD.

See https://math.stackexchange.com/a/319310/430364

There can be no formula that computes lcm(a,b,c) using only the values of abc and gcd(a,b,c) as input.

Therefore, we must compute lcm_of_list from scratch.