5
$\begingroup$

I want to apply Times on the elements of a list such that:

{2,3,5,7,11,13,17,19} => 
{{2,3,5,7,11,13,17,19},{6,35,143,323},{210,46189},{9699690}}

I wrote this function :

listProduct[list_] := 
 Apply[Times, Partition[list, Ceiling[Length[list]/2]]]

Nest[listProduct, {2, 3, 5, 7, 11, 13, 17, 19}, 1]

Using Nest at each level generate the desired element but I am having difficulties with combining the results. Also, I want to be able to use each element once computed.

$\endgroup$
4
  • $\begingroup$ For what it's worth your original version is faster than the answers provided. $\endgroup$
    – Mr.Wizard
    Jan 10, 2013 at 7:28
  • $\begingroup$ @Mr.Wizard my original version is incomplete so I asked how to combine them at once and also how to have access to them once they're computed not at the end. No answer yet. $\endgroup$ Jan 10, 2013 at 8:21
  • $\begingroup$ I didn't understand this part: "I want to be able to use each element once computed." Could you give an example of what you mean? $\endgroup$
    – Mr.Wizard
    Jan 10, 2013 at 9:35
  • $\begingroup$ @Mr.Wizard, it is an iterative computation, as an example when 2*3 => 6 and then 6*35 => 210 I want have access (a simple Print here) to both 6 and 35 in the middle of computation not at the end and using [[]] over the list. $\endgroup$ Jan 10, 2013 at 11:33

3 Answers 3

10
$\begingroup$

You can do :

listProduct2[list_] := Times @@@ Partition[list, 2, 2]

NestList[listProduct2, {2, 3, 5, 7, 11, 13, 17, 19}, 3]
(* {{2, 3, 5, 7, 11, 13, 17, 19}, {6, 35, 143, 323}, {210, 46189}, {9699690}} *)
$\endgroup$
4
$\begingroup$

If you don't want to count how often you have to call the function, you can use FixedPointList which automatically stops when there is nothing more to multiply

FixedPointList[
 Times @@@ Partition[#, 2, 2] &, {2, 3, 5, 7, 11, 13, 17, 19}]
(*
{{2, 3, 5, 7, 11, 13, 17, 19}, {6, 35, 143, 323}, {210, 46189}, 
 {9699690}, {}, {}}
*)

To get rid of the last two empty lists you can use Drop[..,-2]

$\endgroup$
0
$\begingroup$

Using BlockMap:

Clear["Global`*"];
list = {2, 3, 5, 7, 11, 13, 17, 19}
FixedPointList[BlockMap[Apply[Times], #, 2] &, list] // Most // Most

{{2, 3, 5, 7, 11, 13, 17, 19}, {6, 35, 143, 323}, {210, 46189}, {9699690}}


WolframLanguageData["BlockMap"
 , {"VersionIntroduced", "DateIntroduced"}]

{10.2, DateObject[{2015, 7, 14}, "Day", "Gregorian", 5.]}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.