Skip to content

Instantly share code, notes, and snippets.

@athos
Forked from tnoborio/repeating-decimal.clj
Last active September 4, 2017 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save athos/f1f030538a9c5857f76fe6c4f78c51c8 to your computer and use it in GitHub Desktop.
Save athos/f1f030538a9c5857f76fe6c4f78c51c8 to your computer and use it in GitHub Desktop.
(ns repeating-decimal)
(defn repeating-decimal [n]
(loop [rem 1 rems #{} divs [] i 0]
(let [div (int (/ (* rem 10) n))
rem (mod (* rem 10) n)]
(if (and (not= rem 0) (contains? rems rem))
[n divs]
(when (not= rem 0)
(recur rem (conj rems rem) (conj divs div) (inc i)))))))
(comment
(repeating-decimal 7)
(repeating-decimal 11)
(repeating-decimal 12)
(repeating-decimal 97)
)
(defn solve [n]
(loop [i n, m 0, divs []]
(let [l (count divs)]
(if (> i l)
(let [divs' (repeating-decimal i)
l' (count divs')]
(if (> l' l)
(recur (dec i) i divs')
(recur (dec i) m divs)))
[m divs]))))
;; (solve 100000)
@athos
Copy link
Author

athos commented Sep 4, 2017

  • 1/nの循環節の長さはnを超えない
    • 同じ剰余が現れたら循環 ⇒ ありうる剰余は 0n-1n通り
  • つまり、たとえば10000以下の数n1/n10000以上の長さの循環節を持つことはない
  • この性質を利用すれば、100000, 99999, 99998, ..., その時点の循環節の最大長 の範囲の数だけを探索すればいい
    • それ以上小さい値をチェックしても、より長い循環節をもつ数がないことが保証されるため

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment