[Cs254f11] Prime Q
Lee Spector
lspector at hampshire.edu
Mon Sep 26 18:10:16 EDT 2011
You beat me to it, but I didn't notice until I hit send!
-Lee
On Sep 26, 2011, at 6:01 PM, Omri Bernstein wrote:
> I think I can explain what's happening there. Given the set of factors (let's call it S) of n, if you generate a new list by dividing n by each of the elements of S, you will also get a list of the n's factors--only in reverse order from the first one. This is because any number's factors come in pairs. For example, the factors of 7 are 7 and 1, and if you divide 7 by 7 you get 1, and if you divide 7 by 1 you get 7. So what I'm saying is that your function factorsB is generating the factors of a given number, and that first map function in factorsA is generating a list by dividing that number by each of the elements of factorsB--resulting in the same set of numbers in reverse order.
>
> Using the number 10 as an example, here is what's happening after each nested function call in functionB:
> (+ 10 1) => 11
> (range 1 11) => (1 2 3 4 5 6 7 8 9 10)
> (filter #(integer? (/ n %)) '(1 2 3 4 5 6 7 8 9 10)) => (10 5 2 1)
> (map #(/ n %) '(10 5 2 1)) => (1 2 5 10)
>
> -Omri
>
>
> On Mon, Sep 26, 2011 at 3:59 PM, James Matheson <jmatheson12 at gmail.com> wrote:
> So here I have two (working) functions defining the factors (labeled
> factorsA and factorsB) which seem to work exactly the same. However I
> don't map factorsB. Can someone explain to me how map is working here?
>
> (defn factorsB [n]
> (filter #(integer? (/ n %)) (range 1 (+ n 1))))
>
> (defn factorsA [n]
> (map #(/ n %) (filter #(integer? (/ n %)) (range 1 (+ n 1)))))
>
> (defn prime? [n]
> (or (= n 2) (= 2 (count (take 3 (factorsB n))))))
>
> (defn prime-factors [n]
> (filter prime? (factorsB n)))
>
> --Jamie
> _______________________________________________
> Cs254f11 mailing list
> Cs254f11 at lists.hampshire.edu
> https://lists.hampshire.edu/mailman/listinfo/cs254f11
>
> _______________________________________________
> Cs254f11 mailing list
> Cs254f11 at lists.hampshire.edu
> https://lists.hampshire.edu/mailman/listinfo/cs254f11
--
Lee Spector, Professor of Computer Science
Cognitive Science, Hampshire College
893 West Street, Amherst, MA 01002-3359
lspector at hampshire.edu, http://hampshire.edu/lspector/
Phone: 413-559-5352, Fax: 413-559-5438
More information about the Cs254f11
mailing list