ivan milev
ivan milev

Reputation: 9

Compare big integers in array

How to find 3 the biggest BigInteger objects in array? This is my code for now.

package masivi;

import java.math.BigInteger;
import java.util.Scanner;

public class largest3Numbers {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        BigInteger[] numbers = new BigInteger[n];
        BigInteger tempbiggest1 = new BigInteger("0");
        BigInteger biggest1 = new BigInteger("0");
        BigInteger tempbiggest2 = new BigInteger("0");
        BigInteger biggest2 = new BigInteger("0");
        BigInteger tempbiggest3 = new BigInteger("0");
        BigInteger biggest3 = new BigInteger("0");

        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = scan.nextBigInteger();
            if (numbers[i] > tempbiggest1) {

            }
        }
    }
}

Upvotes: 0

Views: 1672

Answers (3)

Hauke S
Hauke S

Reputation: 555

Just use Array.sort to sort the array and take the last three elements in the array:

public class SortBigIntegers {
     public static void main(String[] args) {

        BigInteger[] numbers = new BigInteger[6];
        numbers[0] = new BigInteger("10000000");
        numbers[1] = new BigInteger("200000000");
        numbers[2] = new BigInteger("30000000");
        numbers[3] = new BigInteger("5555555555555");
        numbers[4] = new BigInteger("6666666666");
        numbers[5] = new BigInteger("0");

        Arrays.sort(numbers );

        System.out.println("the three biggest are: " + numbers[5] + ", " + numbers[4] + ", " + numbers[3]);

     }
}

Upvotes: 1

user666
user666

Reputation: 1172

  • First sort the array . You can use one of internal Arrays.sort utility.
  • In the sorted array you can fetch the elements like this .. a[len-1] , a[len-2],a[len-3] where len is yourarray.length

When we use Arrays.sort the elements should be naturally comparable and BigInteger is and implements comparable interface. Thre are few other approaches as well like copying into TreeSet etc but will have more space complexcity.

Upvotes: 0

Jesper
Jesper

Reputation: 206916

This will not compile:

if (numbers[i] > tempbiggest1) {

You cannot use the > operator on BigInteger objects. Use compareTo instead:

// Check if numbers[i] is larger than tempbiggest1
if (numbers[i].compareTo(tempbiggest1) > 0) {

Upvotes: 3

Related Questions