简体   繁体   中英

I have tried using long both as the variable type as well as the return type of the function but still it is overflowing. I cannot understand why?

I am calling the getMaxPairwiseProduct() method and but it is returning overflow value of the "product" variable. I am already using the long and the product actually is in the limits of long but I cannot understand why it is returning overflow value.

import java.util.Scanner;
public class MaxPairwiseProduct {

    static long getMaxPairwiseProduct(int[] array){
        //int product =0 ;
        int n = array.length;
        //for(int j =0; j<n ; ++j){
        //}
        QuickSort(array, 0, array.length -1 );
        int n1 = (array[array.length-1]);
        int n2 = (array[array.length-2]);
         long product =n1 * n2;  
         System.out.println(product);
         return product;
}

        private static void QuickSort(int[] arr,  int left, int right){
            int index = partition(arr,left, right);
            if(left < index - 1)
                QuickSort(arr, left, index -1);
            if(index < right)
                QuickSort(arr, index, right);

            //System.out.println(index);
        }
    private static int partition(int[] arr, int left, int right){
        int pivot = arr[(left + right )/2];
        while(left<=right){
            while(arr[left] < pivot) left++;
            while(arr[right] > pivot) right--;

            if(left<= right){
                int temp= arr[left];
                arr[left] = arr[right];
                arr[right]  =temp;

                left++;
                right--;
            }
        }
        return left;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        /*int n = sc.nextInt();
          int[] array = new int[n];
        for(int i=0; i <n;++i){
          array[i] = sc.nextInt();
         }
         */
        int[] array = new int[]{100000, 90000};
         long product = getMaxPairwiseProduct(array);
         System.out.println(product);
    }
}

Long story short, in Java, every integer (non-decimal) number is treated as int by default, your line:

long product =n1 * n2;  

Will multiply two int values which will overflow and only once the overflowed result is obtained it will be cast to long and saved in product variable.

Fix ?

Cast one of your two operands to long explicitly, something like this would work:

long product = (long)n1 * n2;  

Java will automatically start working with "biggest" data type, so since you are multiplying long and int , the int or n2 will be implicitly converted to long as well, no overflow will occur and you should get correct result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM