Abderrahman Echerif - 1 year ago 61

Java Question

This method is for getting (By input from user) the two largest Integers in the given data set and calculates their product. It works well for every input until I tried the array of two integers

`100000`

`90000`

`410065408`

This is my Java method:

`static int getMaxPairwiseProduct(int[] numbers) {`

int max=0,lessermax=0;

int n = numbers.length;

for (int j = 0; j < n; ++j) {

//if(j==k)continue;

if(numbers[j]>0 && numbers[j]>=max) {

lessermax=max;max=numbers[j];

System.out.println(j);//k=j;

} else if(numbers[j]>lessermax) {

lessermax=numbers[j];

System.out.println(j);}

}

//result=;

return max*lessermax;

}

This is my

`main`

`public static void main(String[] args) {`

//FastScanner scanner = new FastScanner(System.in);

Scanner scanner=new Scanner(System.in);

int n = scanner.nextInt();

int[] numbers = new int[n];

for (int i = 0; i < n; i++) {

numbers[i] = scanner.nextInt();

}

scanner.close();

System.out.println(getMaxPairwiseProduct(numbers));

}

Answer Source

It's overflowing the capacity of `int`

and wrapping around. `100000 * 90000`

is `9000000000`

. The maximum positive value of an `int`

is 2^31-1, which is `2147483647`

(a bit less than quarter of `9000000000`

).

If you want the product of those two numbers, you'll need to use `long`

instead.

```
100000L * 90000L = 9000000000L = 0x218711a00L
```

For 32 bit data type, anything outside the 32 bits (8 hex digits) is chopped off because of overflow. So the value that remains is: `0x18711a00`

== `410065408`