# Multiplying elements of a list

Given I have a following list of numbers:

l={2,3,4,5,6}


I wonder how to multiply each number by the one before of it, such that I get

{2*3,2*3*4,2*3*4*5,...}


Also how can I chose a level for this operation? by level I mean,

level 1 : 2*3

level 2 : 2*3*4

and so on.

FoldList[Times, l] (* or *)
FoldList[Times]@l


{2, 6, 24, 120, 720}

Also:

Exp @ Accumulate @ Log @ l


{2, 6, 24, 120, 720}

list = Range[2, 6]

(* {2, 3, 4, 5, 6} *)


To keep the factors separate, use Inactive with kglr's solution

list2 = Rest@FoldList[Inactive@Times, list[[1]], Rest@list]


Activate produces the result

list3 = list2 // Activate

(* {6, 24, 120, 720} *)


Or use NonCommutativeMultiply to hold the factors

list4 = Rest@FoldList[NonCommutativeMultiply, list[[1]], Rest@list]

(* {2 ** 3, 2 ** 3 ** 4, 2 ** 3 ** 4 ** 5, 2 ** 3 ** 4 ** 5 ** 6} *)


Then Apply Times to get the final result

list5 = Times @@@ list4

(* {6, 24, 120, 720} *)


For this specific case (sequential numbers), the result is just Factorial

list3 == list5 == Factorial /@ Rest@list

(* True *)


Use Part to access any element of the result, e.g.,

list3[[1]]

(* 6 *)


This can also be solved using recursion. The function cumProd (cumulative product) can be defined as:

list = Range[10];
cumProd[n_] := cumProd[n - 1]*list[[n]];
cumProd[1] = list[[1]];


To use:

cumProd[6]
720


gives the 6th "level" of the product. Of course, list can be any set of numbers. Applying this to the whole list:

cumProd/@Range[Length[list]]
{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800}


We can use the MapIndexed function

 list = {2, 3, 4, 5, 6}
f[x_, {i_}] := Times @@ list[[1 ;; i]]
Rest[MapIndexed[f, list, {1}]]


(* 6, 24, 120, 720} *)

level[x_] := Times @@ l[[;; x + 1]];

level[1]
level[2]


6
24

• Using AbsoluteTiming it would seem that the first answer is the fastest: {4.93665*10^-6, {2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800}} even faster than the built-in function Factorial: {0.0000229201, {6, 24, 120, 720, 5040, 40320, 362880, 3628800}} Mar 27, 2019 at 1:34

Using ReplaceList:

list = {2, 3, 4, 5, 6}


Define:

f[k_List] :=
Riffle[k, "*"] // ToString //
StringReplace[#, {"{" -> "", "}" -> "" , "," -> ""}] &

ReplaceList[list
, {a__, b___} :>
{f[{a}], Times @@ {a}}
] // Grid[#, Frame -> All] &


This is for mostly useful for presentation purposes.

f[1]:=1
f[x_] := f[x] = x f[x-1]

l={2,3,4,5,6}
f/@l

(* {2, 6, 24, 120, 720} *)