简体   繁体   中英

Increment a variable by constant in recursive rules in prolog

Here's the line of code written in prolog to make an lcm (Least Common Multiple) rule:

lcm(A, B, A) :-
    A > B,
    A mod B =:= 0, 
    !.

lcm(A, B, B) :-
    B > A,
    B mod A =:= 0,
    !.

lcm(A, B, X) :-
    A < B,
    ImproveB is B + B,
    lcm(A, ImproveB, X).

lcm(A, B, X) :-
    A > B,
    ImproveA is A + A,
    lcm(ImproveA, B, X).

I noticed that there's a bug in these lines of code.

For example, the case is lcm(16,10,X) which operated as below:

  1. lcm(16,10,X).
  2. lcm(32,10,X).
  3. lcm(64,10,X).
  4. lcm(128,10,X).
  5. ...

It will double the larger number and not increment it by the expected constant. The expected operation is as below:

  1. lcm(16,10,X).
  2. lcm(32,10,X).
  3. lcm(48,10,X).
  4. lcm(64,10,X).
  5. lcm(80,10,X).
  6. since 80 mod 10 is 0, so the result of X is 80

So, how to handle this situation?

To solve the problem, the constant value to be added must be passed as an extra argument (which does not change ). Also, to decrease the number of rules, you can fix the order of the arguments so that the first one is the maximum and the second one is the minimum:

lcm(A, B, C) :-
    Min is min(A, B),
    Max is max(A ,B),
    lcm_loop(Max, Min, Max, C).

lcm_loop(A, B, K, C) :-
    (   A mod B =:= 0
    ->  C = A
    ;   A1 is A + K,
        lcm_loop(A1, B, K, C)  ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM