

Clojure Exercise: Calculate Perfect Numbers - mgunes
http://maurits.wordpress.com/2010/09/18/clojure-exercise-calculate-perfect-numbers/

======
aufreak3
That'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]

------
meric
Clojure looks beautiful. How long am I going to put off learning it? Not any
more...

------
ljlolel
Python, 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)))

------
c00p3r

      (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
For 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
Thanks!

btw, it Scheme. Compared to Clojure it is clean and readable.

------
leif
Author 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
I think the point was to introduce the reader to small functions and lazy
lists, not to perfect numbers.

