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:
It will double the larger number and not increment it by the expected constant. The expected operation is as below:
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.