7 ms·
Clojure Exercise: Calculate Perfect Numbers
- leif 16y agoAuthor pretty clearly knows very little about number theory. It needs a lot of optimization, pruning, and caching to be useful. Nice simple lisp intro though.
- jrockway 16y agoI think the point was to introduce the reader to small functions and lazy lists, not to perfect numbers.
- meric 16y agoClojure looks beautiful. How long am I going to put off learning it? Not any more...
- c00p3r 16y ago(define (perfect-numbers integers) (stream-filter perfect? (stream-cdr integers))) (define (perfect? n) (= n (sum-stream (stream-filter (lambda (x) (zero? (remainder n x))) (stream-range 1 (+ (/ n 2) 1))))))) Happy Happy Joy Joy!
- drunkpotato 16y agoFor the first, you don't need to wrap a function of one argument in a lambda. I can't remember if you need to quote function names in Clojure, so it's either: (stream-filter perfect? ... ) or: (stream-filter 'perfect? ...)
- c00p3r 16y agoThanks! btw, it Scheme. Compared to Clojure it is clean and readable.
- aufreak3 16y agoThat's a school exercise, but I can't resist adding a haskell version - perfects = [n | n <- [1..], n == sum (divisors n)] where divisors n = [k | k <- [1..(n `div` 2)], n `mod` k == 0]
- ljlolel 16y agoPython, arguable most readable: divisors = lambda n: (k for k in range(1, n / 2 + 1) if n % k == 0) perfects = (n for n in itertools.count(1) if n == sum(divisors(n)))