Created
January 1, 2020 07:26
-
-
Save hindol/f918b382b94dd1f5d98306195f231128 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 com.github.hindol.euler | |
(:require | |
[clojure.test :refer [is]] | |
[clojure.tools.trace :refer [trace-ns untrace-ns]]) | |
(:gen-class)) | |
(set! *unchecked-math* true) | |
(set! *warn-on-reflection* true) | |
(defn pentagonal-seq | |
[] | |
(let [xf (comp | |
(mapcat (juxt identity -)) | |
(map #(/ (* % (dec (* 3 %))) 2)))] ;; k (3k - 1) / 2 | |
(sequence xf (iterate inc 1)))) | |
(def cached-pentagonal-seq | |
(pentagonal-seq)) | |
;; https://projecteuler.net/problem=78 | |
;; | |
;; * | |
;; | |
;; ** | |
;; * * | |
;; | |
;; *** | |
;; ** * | |
;; * * * | |
;; | |
;; **** | |
;; *** * | |
;; ** ** | |
;; ** * * | |
(def count-partitions | |
"Given n coins, how many distinct partitions are possible?" | |
(memoize | |
(fn | |
[n] | |
{:pre [(is (not (neg? n)))] | |
:post [(is (not (neg? %)))]} | |
(cond | |
(neg? n) 0 | |
(zero? n) 1 | |
:else (let [xf (comp | |
(take-while #(<= % n)) | |
(map #(count-partitions (- n %)))) | |
terms (sequence xf cached-pentagonal-seq) | |
signs (cycle [+1 +1 -1 -1])] | |
(reduce +' (map * signs terms))))))) | |
(defn -main | |
[& _] | |
(let [n 6 | |
xf (comp | |
(map count-partitions) | |
(take-while #(pos? (rem % 1000000))))] | |
(+ n (count (sequence xf (iterate inc n)))))) | |
(time (-main)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For posterity, here it is with the transducer:
Takes 4.2s on my machine.