Time to get my repl up and running. Not very clean, but gets the job done. Here's some Clojure:
(ns kaprekar) (defn is-kap? [n] (let [square (* n n) ss (str square) length (count ss) ss (if (odd? length) (str "0" ss) ss) length (count ss) half-length (/ length 2) first-half (bigint (subs ss 0 half-length)) second-half (bigint (subs ss half-length))] (= n (+ first-half second-half)))) (defn find-kaps [] (loop [i 1 found 0] (if (is-kap? i) (do (println i) (when (< found 7) (recur (inc i) (inc found)))) (recur (inc i) found))))
Thanks to Richard Orelup' tip to zero-pad the number if its length is odd.
Taking inspiration from Thomas Much's answer, I refactored my code to be more functional-esque and idiomatic:
(ns kaprekar) (defn is-kap? [n] (let [square (* n n) ss (str square) length (count ss) ss (if (odd? length) (str "0" ss) ss) length (count ss) half-length (/ length 2) first-half (bigint (subs ss 0 half-length)) second-half (bigint (subs ss half-length))] (= n (+ first-half second-half)))) (defn find-kaps [] (->> (iterate inc 1) (filter is-kap?) (take 8) (run! println)))
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Time to get my repl up and running. Not very clean, but gets the job done. Here's some Clojure:
Thanks to Richard Orelup' tip to zero-pad the number if its length is odd.
Taking inspiration from Thomas Much's answer, I refactored my code to be more functional-esque and idiomatic: