The biggest common factor in Clojure

I wrote the following code to calculate the Large common divisor of two positive numbers. Are there any issues in the code that are not optimal or complex enough, and if so, what would be a more cloujerian way of doing GCD?

(def gcd (fn [ab] (->> (map (fn [x] (filter #(zero? (mod x %)) (range 1 (inc x)))) [ab]) (map set) (apply clojure.set/intersection) (apply max)))) (gcd 1023 858)` => 33 
+5
source share
3 answers

using sequence manipulation for numerical operations (without converters) is a bit heavyweight, and this would be a great example for recur instead:

 user> (defn gcd [ab] (if (zero? b) a (recur b (mod ab)))) #'user/gcd user> (gcd 1023 858) 33 

This saves some effort / time that will be built into the build sequences, which are then discarded. In this case, he creates a sequence of two sequences of numbers, turns them into a sequence of two sets, and then splits them into one set, of which the largest value is the answer.
In addition, in the general case, when defining a vars containing functions, use defn (short for the define function), it automatically adds interesting things that help the tools a lot, for example, displaying types of arguments, etc.

+5
source

This is what I did, it is a little shorter and does not use recursion:

 (defn gcd [ab] (last (filter #(and (zero? (mod b %)) (zero? (mod a %))) (range 1 (inc (min ab))) ) ) ) 
0
source
 (loop [a (map #(Integer/parseInt %) (clojure.string/split (read-line) #" "))] (cond (reduce > a) (recur (list (reduce - a) (last a))) (reduce < a) (recur (list (- (reduce - a)) (first a))) (reduce = a) (println (first a)))) 
-1
source

All Articles