Abderrahman Echerif
Abderrahman Echerif

Reputation: 11

Multiplying two large integer values gives incorrect result

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 and 90000 where it returns 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 method:

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

Upvotes: 0

Views: 1830

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074435

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

Upvotes: 5

Related Questions