On Sat, Jul 25, 2009 at 4:40 PM, atucker <[email protected]> wrote:
>
> I wonder if any of the Clojurians on here might like to describe how
> one might write the factorial function as a parallel one? Taking
> advantage of the associativity of multiplication, along the lines of
>
> 16! = (((1*2)*(3*4)) * ((5*6)*(7*8))) * (((9*10)*(11*12)) * ((13*14)*
> (15*16)))
>
(defn factorial [n]
(let [cores (.. Runtime (getRuntime) (availableProcessors))]
(if (< n (* 2 cores))
(reduce * (rest (range (inc n))))
(let [parts (pmap #(reduce * %) (partition (quot (inc n) cores) (rest
(range (inc n)))))]
(reduce * parts)))))
ought to do it.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---