Skip to content

Instantly share code, notes, and snippets.

@c-spencer
Created July 16, 2010 09:57
Show Gist options
  • Save c-spencer/478196 to your computer and use it in GitHub Desktop.
Save c-spencer/478196 to your computer and use it in GitHub Desktop.
; memoize this
(defn collatz [n l]
(if (= n 1)
(inc l)
(if (even? n)
(recur (/ n 2) (inc l))
(recur (inc (* 3 n)) (inc l)))))
(print (time
(apply max-key last
(map (fn [n] [n (collatz n 0)]) (range 1 1000001)))))
(defn pow2 [c n]
(if (= n 0)
c
(recur (* c 2) (dec n))))
(defn sum-digits [x]
(apply + (map #(Integer. (str %)) (seq (str x)))))
(print (time
(sum-digits (pow2 1 1000))))
(defn fact [c n]
(if (= n 0)
c
(recur (* c n) (dec n))))
(print (time
(sum-digits (fact 1 100))))
(def fibs
(lazy-cat [1 1]
(map + fibs (rest fibs))))
(defn pow [n power c]
(if (= power 0)
c
(recur n (dec power) (* n c))))
(let [limit (pow 10 999 1)]
(inc (count (take-while #(if (< % limit) %) fibs))))
(defmacro defn+ [name args & body]
`(def ~name
(memoize
(fn ~args
~@body))))
(defn+ prime? [x]
(every? #(pos? (rem x %)) (range 2 (+ 1 (. Math ceil (. Math sqrt x))))))
(def composite?
(complement prime?))
(defn next-prime [x]
(some #(if (prime? %) %) (iterate inc (inc x))))
(defn prime-seq []
(iterate next-prime 2))
(defn+ square? [x]
(== (#(* % %) (. Math floor (. Math sqrt x))) x))
(defn diff-double-square? [x p]
(let [diff (- x p)]
(and (even? diff) (square? (quot diff 2)))))
(defn golbach? [x]
(some
#(if % x)
(pmap
#(diff-double-square? x %)
(take-while #(< % x) (prime-seq)))))
(some #(if (golbach? %) nil %) (filter composite? (iterate #(+ % 2) 1)))
(reduce #(+ %1 (pow %2 %2 1)) 0 (range 1 1001))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment