Skip to content

Instantly share code, notes, and snippets.

@littleredcomputer
Last active August 29, 2015 14:14
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 littleredcomputer/9fed7db435d24522fbdb to your computer and use it in GitHub Desktop.
Save littleredcomputer/9fed7db435d24522fbdb to your computer and use it in GitHub Desktop.
Egyptian fractions in Clojure
(ns ef
(:require [clojure.math.numeric-tower :as nt]))
(defn ef [r]
(loop [r r ef []]
(let [x (numerator r)
y (denominator r)]
(if (= x 1) (conj ef r)
(recur (/ (mod (- y) x) (* y (nt/ceil (/ y x))))
(conj ef (/ (nt/ceil (/ y x)))))))))
(defn ef-lazy [r]
(let [x (numerator r)]
(if (= x 1) (list r)
(let [y (denominator r)
z (nt/ceil (/ y x))]
(cons (/ z) (lazy-seq (ef-lazy (/ (mod (- y) x) (* y z)))))))))
(defn ef-max-denom [r]
(-> r ef-lazy last denominator))
(first (reduce (partial max-key second)
(map (juxt identity ef-max-denom)
(for [d (range 1 100) n (range 1 d)] (/ n d)))))
;=> 8/97
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment