Search code examples
prologlcm

PROLOG - LCM of couples in list


I want to find the Least Common Multiple (LCM) of couples from a list. But in the following way:

For example if I have this list:

L1 = [1,2,3,4,5].

I want to produce this list:

L2 = [1,2,6,12,60].

I use the first element of L1 as first element of L2 and the rest follow this form:

L2[0] = L1[0]
L2[i+1] = lcm( L1[i+1] , L2[i] )

Here is what I've done so far, but it doesn't work. Always printing false.

%CALL_MAKE----------------------------------------
%Using call_make to append Hd to L2 list

call_make([Hd|Tail], Result) :-
    make_table(Tail, [Hd], Result).

%MAKE_TABLE---------------------------------------
%Using make_table to create the rest L2
    make_table([],Res,Res).
    make_table([Head|Tail], List, Result) :-
        my_last(X, List),
        lcm(Head, X, R),
        append(List, R, Res),
        make_table(Tail, Res, Result).

%last element of a list---------------------------
    my_last(X,[X]).
    my_last(X,[_|L]):- my_last(X, L).

%GCD----------------------------------------------
    gcd(X, 0, X) :- !.
    gcd(X, Y, Z) :-
        H is X rem Y,
        gcd(Y, H, Z).

%LCM----------------------------------------------
    lcm(X,Y,LCM):-
        gcd(X,Y,GCD),
        LCM is X*Y//GCD.

I want to run the program and get this:

?- call_make([1,2,3,4,5], Result).
Result = [1,2,6,12,60].

Solution

  • append/3 is taking two lists to concatenate, while here:

    append(List, R, Res),
    

    R is a scalar. Change it to

    append(List, [R], Res),