Search code examples
javamultiplication

How to multiply two long values in java


I am trying to multiply two largest numbers from an array of numbers. Its working fine for small numbers.

Correct input / output - this is working:

3 10 2 8 80

Correct input / output - this is failing:

2 100000 90000
9000000000

My output is however 10000000000 instead.

Can someone tell me what is wrong in my code?

public static Long sumPairwise(Long[] numbers){

        int index=0;
        int n = numbers.length;
        for(int i=1;i<n;i++){
            if(numbers[i]>numbers[index])
                    index=i;
        }
        numbers[n-1]= numbers[index];
        index=0;
        for(int j=1;j<n-1;j++){
        if(numbers[j]>numbers[index])
                index=j;
        }
        numbers[n-2]=numbers[index];
        Long product = (numbers[n-2])*(numbers[n-1]);

    return product ;
}
public static void main(String [] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    Long numbers[] = new Long[n];
    for (int i=0;i<n;i++)
    numbers[i]= sc.nextLong();
    System.out.println(sumPairwise(numbers));

}

Solution

  • You are replacing the original number in that index with another number. That is causing the issue.

    Please just simply find the max 2 numbers from below logic and multiply. Also, remember to close scanner.

    Here the simple solution. This will work only for positive integers.

    import java.util.Scanner;
    
        public class Snippet {
            public static long multiplyHighestTwoValues(Long[] numbers) {
    
                long maxOne = 0;
                long maxTwo = 0;
                for (long n : numbers) {
                    if (maxOne < n) {
                        maxTwo = maxOne;
                        maxOne = n;
                    } else if (maxTwo < n) {
                        maxTwo = n;
                    }
                }
    
                long product = maxOne * maxTwo;
                return product;
            }
    
            public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                int n = sc.nextInt();
                Long numbers[] = new Long[n];
                for (int i = 0; i < n; i++)
                    numbers[i] = sc.nextLong();
                System.out.println(sumPairwise(numbers));
                sc.close();
    
            }
        }