Working on getting better at Clojure so thought I'd give it a shot.
(ns philip.perfect-numbers) (defn brute-force-perfect-number? [num] (== num (apply + (filter #(zero? (mod num %)) (range 1 (inc (/ num 2))))))) (time (println (take 4 (filter brute-force-perfect-number? (iterate inc' 2))))) ; (6 28 496 8128) ; "Elapsed time: 2649.69715 msecs" (defn perfect-number? [num] (loop [divisor 2 subtotal 1] (let [ q (quot num divisor) evenly-divisible? (zero? (mod num divisor))] (if (>= divisor q) (== num subtotal) (recur (inc divisor) (if evenly-divisible? (+ subtotal divisor q) subtotal)))))) (time (println (take 4 (filter perfect-number? (iterate inc' 2))))) ; (6 28 496 8128) ; "Elapsed time: 66.942315 msecs"
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Working on getting better at Clojure so thought I'd give it a shot.