Skip to content

Instantly share code, notes, and snippets.

@bobbicodes
Last active January 13, 2019 18:22
Show Gist options
  • Save bobbicodes/50ffdd75e03597f1256df6a8bda08fc8 to your computer and use it in GitHub Desktop.
Save bobbicodes/50ffdd75e03597f1256df6a8bda08fc8 to your computer and use it in GitHub Desktop.
Functions for doing simple math problems
(defn gcd [a b]
(if (zero? b)
a
(recur b (mod a b))))
(defn factors [num]
(loop [n num div 2 divs '()]
(cond (<= n 1) divs
(zero? (rem n div)) (recur (/ n div) div (cons div divs))
:else (recur n (inc div) divs))))
(defn abs [x]
(if (< x 0) (- x) x))
(defn pow [x n]
(Math/pow x n))
; https://rosettacode.org/wiki/Nth_root#Clojure
(defn calc-delta [A x n]
(/ (- (/ A (pow x (- n 1)))
x)
n))
(defn nth-root
" nth root of algorithm: A = numer, n = root"
([A n] (nth-root A n 0.5 1.0)) ; Takes only two arguments A, n and calls version which takes A, n, guess-prev, guess-current
([A n guess-prev guess-current] ; version take takes in four arguments (A, n, guess-prev, guess-current)
(if (< (abs (- guess-prev guess-current)) 1e-6)
guess-current
(recur A n guess-current (+ guess-current (calc-delta A guess-current n)))))) ; iterate answer using tail recursion
(defn sqrt [n]
(nth-root n 2))
(defn cbrt [n]
(nth-root n 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment