From 9080533799744102af06f25939abf2c9a35fd832 Mon Sep 17 00:00:00 2001 From: AlvinIndrawan <86299016+AlvinIndrawan@users.noreply.github.com> Date: Sun, 2 Oct 2022 14:07:50 +0700 Subject: [PATCH] Add Greatest Common Divisor and Least Common Multiple --- algorithms/math/Greatest-Common-Divisor.clj | 13 +++++++++ algorithms/math/Least-Common-Multiple.clj | 29 +++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 algorithms/math/Greatest-Common-Divisor.clj create mode 100644 algorithms/math/Least-Common-Multiple.clj diff --git a/algorithms/math/Greatest-Common-Divisor.clj b/algorithms/math/Greatest-Common-Divisor.clj new file mode 100644 index 0000000..2bb56ac --- /dev/null +++ b/algorithms/math/Greatest-Common-Divisor.clj @@ -0,0 +1,13 @@ +(ns math.Greatest-Common-Divisor) + +;; Given two integers, write a function which returns the greatest common divisor. + +(defn GCM [x y] + (if (= y 0) + x + (GCM y (mod x y)))) + +;; (= (GCM 2 4) 2) +;; (= (GCM 10 5) 5) +;; (= (GCM 5 7) 1) +;; (= (GCM 1023 858) 33) \ No newline at end of file diff --git a/algorithms/math/Least-Common-Multiple.clj b/algorithms/math/Least-Common-Multiple.clj new file mode 100644 index 0000000..8a9c47c --- /dev/null +++ b/algorithms/math/Least-Common-Multiple.clj @@ -0,0 +1,29 @@ +(ns math.Least-Common-Multiple) + +;; Write a function which calculates the least common multiple. Your function should accept a variable number of positive integers or ratios. + +(defn LCM [& arg] + ((fn kpk [& data] + (let [data-first (nth data 0) + data-new (nth data 1) + normal-data (flatten data-new) + x (vec normal-data)] + (let [check (for [i (range (dec (count x)))] + (if (= (x i) (x (inc i))) + true + false)) + lowest (apply min x)] + (if (some #(= false %) check) + (kpk data-first + (for [i (range (count x))] + (if (= (x i) lowest) + (+ (x i) (nth data-first i)) + (x i)))) + (x 0))))) + (vec arg) (vec arg))) + +;; (== (LCM 2 3) 6) +;; (== (LCM 5 3 7) 105) +;; (== (LCM 1/3 2/5) 2) +;; (== (LCM 3/4 1/6) 3/2) +;; (== (LCM 7 5/7 2 3/5) 210) \ No newline at end of file