0

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.
  • There's a tiny Prolog script at https://codegolf.stackexchange.com/questions/94999/least-common-multiple (not that it's optimized for speed or readability). General principle is at https://www.reddit.com/r/prolog/comments/s21hjl/how_to_write_a_recursive_lowest_common_multiple/hsceshl/ – brebs Mar 06 '22 at 16:44

1 Answers1

0
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.

chansey
  • 1,266
  • 9
  • 20