Files
2024-08-31 12:07:21 +03:00

38 lines
1.3 KiB
Common Lisp

;15. Determine the least common multiple of the numerical values of a nonlinear list.
; mygcd(a, b) = a, if b = 0
; = mygcd(b, a mod b), otherwise
(defun mygcd (a b)
(cond ((= 0 b) a)
(t (mygcd b (mod a b)))))
; mylcm(a, b) = a * b / mygcd(a, b)
(defun mylcm (a b)
(/ (* a b) (mygcd a b)))
; least-common-multiple(lst) = 1, if lst = ()
; = lst, if lst is atom and number and not 0
; = error, if lst is atom and not number or 0
; = mylcm(least-common-multiple(car lst), least-common-multiple(cdr lst)), otherwise
(defun least-common-multiple (lst)
(cond ((null lst) 1)
((and (atom lst) (numberp lst) (not (= 0 lst))) lst)
((atom lst) 1)
(t (mylcm (least-common-multiple (car lst))
(least-common-multiple (cdr lst))))))
; least-common-multiple-main(lst) = error, if lst = ()
; = least-common-multiple(lst), otherwise
(defun least-common-multiple-main (lst)
(cond ((null lst) (error "Invalid argument"))
(t (least-common-multiple lst))
))
(print (least-common-multiple-main '(12 2 4 6 8)))
(print (least-common-multiple-main '(4 10 (5 6) 2)))
(print (least-common-multiple-main '(1 A (2 3 B 6) 5)))
(print (least-common-multiple-main '(1(2(3(4(F)5)6)1)1)))
(exit)