Last active
January 9, 2020 10:17
-
-
Save serioga/aea576577535c79c75e0d81987601e9a to your computer and use it in GitHub Desktop.
Armstrong
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 task.armstrong | |
"Task description: create function to check if integer is an | |
armstrong number https://en.wikipedia.org/wiki/Narcissistic_number. | |
For https://t.me/clojure_ru/103457." | |
(:require | |
[clojure.test :as t])) | |
(set! *warn-on-reflection* true) | |
(defn digits-base-10 | |
"Convert integer to sequence of its digits in base 10." | |
{:test (fn [] | |
(t/is (= '(1 2 3) (digits-base-10 123))))} | |
[n] | |
(loop [n' n | |
result (list)] | |
(if (pos? n') | |
(recur (quot n' 10) (conj result (rem n' 10))) | |
result))) | |
(defn exponent | |
"Calculate exponent `e` for integer `n`. | |
`Math/pow` does not work correctly for large `e` and `n` like 9^17." | |
{:test (fn [] | |
(t/is (= 16677181699666569 (exponent 17 9))))} | |
[e n] | |
(.pow (biginteger n) e)) | |
(defn narcissistic-base-10 | |
"Calculate narcissistic function https://en.wikipedia.org/wiki/Narcissistic_number#Definition for base 10." | |
{:test (fn [] | |
(t/is (= 548834 | |
(narcissistic-base-10 548834))) | |
(t/is (= 21897142587612075 | |
(narcissistic-base-10 21897142587612075))) | |
(t/is (= 115132219018763992565095597973971522401 | |
(narcissistic-base-10 115132219018763992565095597973971522401))))} | |
[n] | |
(let [xs (digits-base-10 n) | |
e (count xs)] | |
(transduce (map (partial exponent e)) + xs))) | |
(defn armstrong? | |
{:test (fn [] | |
(t/is (armstrong? 21897142587612075)))} | |
[n] | |
(= n (narcissistic-base-10 n))) | |
#_(comment | |
(t/run-tests) | |
(armstrong? 21897142587612075) | |
(armstrong? 115132219018763992565095597973971522401)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment