Last active
August 29, 2015 14:14
-
-
Save littleredcomputer/9fed7db435d24522fbdb to your computer and use it in GitHub Desktop.
Egyptian fractions in Clojure
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 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