Created
April 28, 2012 00:45
-
-
Save awostenberg/2514719 to your computer and use it in GitHub Desktop.
happy primes Clojure Dr. Who
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
| ;;Happy primes: inspired by watching Dr. Who episode 7 season 3 with my youngest son, John, on netflix | |
| ;;"don't they teach recreational mathematics any more?" -- Dr. Who, "42" | |
| ;;http://en.wikipedia.org/wiki/42_(Doctor_Who) | |
| ;;http://www.wolframalpha.com/input/?i=happy+numbers | |
| ;;Code was written in just the order you see things here, | |
| ;;in the bottom-up style of programming typical of Lisp and Smalltalk | |
| ;;In this recreational style I don't write tests, | |
| ;; but leave commented expressions you could evaluate near each function. | |
| ;;for serious work I'd move these into Clojure Midge unit tests | |
| ;;This works well in Emacs with Slime and Swank Clojure | |
| ;; (http://dev.clojure.org/display/doc/Getting+Started+with+Emacs) | |
| ;;alternately for a quick start you could paste these defn's over to www.tryclj.com one at a time, | |
| ;;and use the examples following each defn here to play around and learn it the way it was built: bottom up | |
| (defn remainders | |
| "answer vector of remainders when N is divided by 2..n/2" | |
| [n] (map (partial mod n) (range 2 (inc (/ n 2))))) | |
| ;;(remainders 10) | |
| (defn prime? | |
| "answer true if n is prime" | |
| [n] (every? (complement zero?) (remainders n))) | |
| ;;(prime? 2) | |
| ;;(prime? 4) | |
| ;;take first primes of infinite lazy sequence of them | |
| ;;(take 50 (filter prime? (iterate inc 1))) | |
| (defn digit | |
| "answer numeric digit for ascii character c" | |
| [c] | |
| (- (int c) (int \0))) | |
| ;;(digit \1) | |
| (defn digits | |
| "answer vector of digits for number n" | |
| [n] | |
| (map digit (str n))) | |
| ;;(digits 1234) | |
| (defn sum-square-digits [n] (reduce + (map #(* % %) (digits n)))) | |
| ;;(sum-square-digits 19) | |
| ;;(take 10 (iterate sum-square-digits 19)) | |
| ;;(take 15 (iterate sum-square-digits 81)) | |
| (defn happy? | |
| "answer true if n is a happy number" | |
| ([n] (happy? n [])) | |
| ([n history] | |
| (if (= n 1) | |
| true | |
| (if (some #{n} history) | |
| false | |
| (happy? (sum-square-digits n) (cons n history)))))) | |
| ;;(happy? 1) | |
| ;;(happy? 19) | |
| ;;(happy? 81) | |
| ;;"a happy prime is one that is both happy and prime" -- Dr. Who | |
| (defn happy-prime? [n] (and (happy? n) (prime? n))) | |
| ;;(happy-prime? 7) | |
| ;;so was Dr. Who right in the televised episode? Find the happy primes beginning around 300 | |
| ;;(take 5 (filter happy-prime? (iterate inc 300))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment