Skip to content

Instantly share code, notes, and snippets.

@zwang
Last active August 29, 2015 14:06
Show Gist options
  • Save zwang/7bc9031306b7f39142f0 to your computer and use it in GitHub Desktop.
Save zwang/7bc9031306b7f39142f0 to your computer and use it in GitHub Desktop.
To calculate the largest prime factor of a number
(ns scratch.core)
(defn dividable? [number]
#(zero? (mod number %))
)
(defn dividableByAny? [number divList]
(> (count (filter (dividable? number) divList)) 0)
)
(defn getAllPrimes [number]
(loop [i 2, list '()]
(if (<= i number)
(if (dividableByAny? i list)
(recur (inc i) list)
(recur (inc i) (conj list i))
)
list
)
)
)
(defn isPrime? [number]
(let [x (Math/sqrt number)]
(not (some (dividable? number) (getAllPrimes x)))
)
)
(defn getFactors [number]
(loop [i 2 x number list '()]
(let [div? (dividable? x)]
(if (<= i (Math/sqrt number))
(if (div? i)
(do ;(println i (/ x i))
(recur i (/ x i) (conj list i (/ x i)))
)
(recur (inc i) x list)
)
list
)
)
)
)
;(getLargestFactor 600851475143) ;6857
(defn getLargestFactor [number]
(let [f (getFactors number) bar (if (zero? (count f)) (conj f number) f)]
(apply max (filter isPrime? bar))
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment