7
$\begingroup$

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.

$\endgroup$
7
$\begingroup$
FoldList[Times, l] (* or *)
FoldList[Times]@l

{2, 6, 24, 120, 720}

Also:

Exp @ Accumulate @ Log @ l

{2, 6, 24, 120, 720}

$\endgroup$
4
$\begingroup$
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]

enter image description here

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 *)
$\endgroup$
3
$\begingroup$

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}
$\endgroup$
2
$\begingroup$

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} *)

$\endgroup$
1
$\begingroup$

here is your level function

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

level[1]
level[2]   

6
24

$\endgroup$

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

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