Home > Blockchain >  How to multiply all the values in an array together in java
How to multiply all the values in an array together in java

Time:04-30

Say I have some array

int[] arr = {3,7,10,2};

And I want to create a loop to multiply each value to get the product (in this case 420) what would that loop look like?

EDIT: a BigInteger will be required for the program I am trying to write

CodePudding user response:

import java.math.BigInteger;
public class Multiply {
    public static void main(String[] args)  {
        int[] arr = {3,7,10,2};
        BigInteger mul = BigInteger.valueOf(1); // neutral element as start value
        for (int i : arr) { // iterate over array 
            mul = mul.multiply(BigInteger.valueOf(i));
        }
        System.out.println(mul);
    }
}

produces

$ java Multiply.java
420

CodePudding user response:

Stream#reduce can do the math repetitively.

Make example input data.

List< BigInteger > inputs =
    List.of( 
        new BigInteger( "3" ) , 
        new BigInteger( "7" ) , 
        new BigInteger( "10" ) , 
        new BigInteger( "2" ) 
    ) ;

Make a stream of that list of inputs. Apply the multiply method.

Optional< BigInteger > result = 
    inputs 
    .stream()
    .reduce( BigInteger :: multiply )
;

See this code run live at IdeOne.com.

Optional[420]

  • Related