Created
December 19, 2017 23:19
-
-
Save bradcypert/35ac4380b49a1d19931813887cad6ee4 to your computer and use it in GitHub Desktop.
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 sumofcubes.core) | |
(def TWO (BigDecimal. 2)) | |
(def SQRT_DIG (BigDecimal. 150)) | |
(def SQRT_PRE (.pow BigDecimal/TEN (.intValue SQRT_DIG))) | |
(def PRECISION (.divide BigDecimal/ONE SQRT_PRE)) | |
(def eight (BigDecimal. 8)) | |
(def neg-one (BigDecimal. -1)) | |
(def one BigDecimal/ONE) | |
(def half (BigDecimal. 0.5)) | |
(defn big-sqrt [c] | |
(if (neg? c) Double/NaN | |
(loop [xn BigDecimal/ONE] | |
(let [fx (-> xn | |
(.pow TWO) | |
(.add (.negate c))) | |
fpx (.multiply xn TWO)] | |
(let [xn1 (-> fx | |
(.divide fpx | |
(-> SQRT_DIG | |
(.multiply TWO) | |
(.intValue)) | |
BigDecimal/ROUND_HALF_DOWN) | |
(.add (.negate xn))) | |
current-precision (.abs (.subtract (.pow xn1 2) c))] | |
(if (neg? (.compareTo current-precision PRECISION)) xn1 (recur xn1))))))) | |
(defn sum-of-cubes [n] | |
(-> n | |
(.multiply n) | |
(.multiply (.add n BigInteger/ONE)) | |
(.multiply (.add n BigInteger/ONE)) | |
(.divide (BigInteger. "4")))) | |
(defn calc-a [m] | |
(let [step1 (-> m | |
(big-sqrt) | |
(.multiply eight) | |
(.multiply neg-one) | |
(.add one))] | |
(if (neg? step1) Double/NaN | |
(-> step1 | |
(big-sqrt) | |
(.multiply neg-one) | |
(.subtract one) | |
(.multiply half))))) | |
(defn calc-b [m] | |
(let [step1 (-> m | |
(big-sqrt) | |
(.multiply eight) | |
(.multiply neg-one) | |
(.add one))] | |
(if (neg? step1) | |
Double/NaN | |
(-> step1 | |
(big-sqrt) | |
(.subtract one) | |
(.multiply half))))) | |
(defn calc-c [m] | |
(let [step1 (-> m | |
(big-sqrt) | |
(.multiply eight) | |
(.add one))] | |
(if (neg? step1) | |
Double/NaN | |
(-> step1 | |
(big-sqrt) | |
(.multiply neg-one) | |
(.subtract one) | |
(.multiply half))))) | |
(defn calc-d [m] | |
(let [step1 (-> m | |
(big-sqrt) | |
(.multiply eight) | |
(.add one))] | |
(if (neg? step1) | |
Double/NaN | |
(-> step1 | |
(big-sqrt) | |
(.subtract one) | |
(.multiply half))))) | |
(defn find-nb [m] | |
(let [big-m (if (= (type m) BigDecimal) m (BigDecimal. (str m))) | |
a (calc-a big-m) | |
b (calc-b big-m) | |
c (calc-c big-m) | |
d (calc-d big-m) | |
candidate (apply max (remove #(= Double (type %)) [a b c d]))] | |
(if (.equals (sum-of-cubes (.toBigInteger candidate)) (.toBigInteger big-m)) (bigint candidate) -1))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment