Saturday, April 28, 2012

Divisibility operations

Divide, undivide, factorize, and unfactorize are partition relations. Division takes a natural number and it splits it into quotient and remainder parts and the gcd function splits an unordered pair of numbers into the gcd and a fractional part. Fractional parts are useful in dealing with gunk mereology and the field of rational numbers.
(defn divide
  (fn [a]
    {:q (quot a n), 
     :r (rem a n)}))

(defn undivide 
  (fn [a]
    (+ (* n (:q a)) (:r a)))

(defn divides?
  [a b]

  (zero? (:r ((divide b) a))))

(defn divisors
  (filter (partial divides? n) (range 1 (inc n))))

(defn common-divisors
  [& nums]

  (apply clojure.set/intersection (map (comp set divisors) nums)))

(defn factorize-pair

  (let [gcd (apply max (apply common-divisors a))]
    {:gcd gcd,
     :fp (sort < (map (partial * (/ gcd)) a))}))

(defn unfactorize-pair
  (map (partial * (:gcd a)) (:fp a)))

No comments:

Post a Comment