Last active
August 29, 2015 13:58
-
-
Save pqnelson/10039472 to your computer and use it in GitHub Desktop.
Math helps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns math-helper | |
:require [clojure.set :as set-utils]) | |
(defn float? [x] (instance? java.lang.Float x)) | |
(defn double? [x] (instance? java.lang.Double x)) | |
(defmacro defconst [const-name const-val] | |
`(def | |
~(with-meta const-name | |
(assoc (meta const-name) :const true)) | |
~const-val)) | |
(defconst machine-epsilon 2.220446049250313E-16) | |
(defconst sqrt-machine-epsilon 1.4901161193847656E-8) | |
(defn abs [x] | |
(if (neg? x) (- x) x)) | |
(defn sq [x] (* x x)) | |
;; See Knuth, vol 2 | |
(defn float-compare | |
([a b] (float-compare a b sqrt-machine-epsilon)) | |
([a b eps] | |
(let [exponent (Math/get-exponent (if (> (abs a) (abs b)) a b)) | |
delta (Math/scalb eps exponent) | |
diff (- a b)] | |
(cond | |
(> diff delta) 1 | |
(< diff (- delta)) -1 | |
0)))) | |
(defn float= | |
([a b] (zero? (float-compare a b sqrt-machine-epsilon))) | |
([a b eps] (zero? (float-compare a b eps)))) | |
;; set theoretic related stuff | |
(defn power-set [S] | |
(if (empty? S) | |
#{#{}} | |
(let [e (first S) | |
T (disj S e)] | |
(set-utils/union (power-set T) ; BUG: may blow the stack, and redundant | |
(set (map #(conj % e) (power-set T))))))) | |
;; number theoretic stuff | |
(defn gcd | |
"(gcd a b) computes the greatest common divisor of a and b." | |
[a b] | |
(if (zero? b) | |
a | |
(recur b (mod a b)))) | |
(defn lcm [a b] | |
(let [x (gcd a b)] | |
(* (/ a x) | |
(/ b x) | |
x))) | |
(defn coprime? [a b] | |
(= 1 (gcd a b))) | |
(defn totient [x] | |
(->> (range 1 x) | |
(filter (partial coprime? x)) | |
count)) | |
(defn get-digits [n] | |
(some->> (str n) | |
seq | |
(map str) | |
(map read-string))) | |
(defn happy? [n] | |
(let [sum-sq-digits #(reduce + (map sq (get-digits %)))] | |
(loop [S #{} | |
k n] | |
(cond | |
(= 1 k) true | |
(contains? S k) false | |
:else (recur (conj S k) (sum-sq-digits k)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment