0

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) {

            }
        }
    }
}
0

3 Answers 3

3

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) {
Sign up to request clarification or add additional context in comments.

Comments

1

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

     }
}

Comments

0
  • 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.

2 Comments

That's probably an overkill to sort the whole array just to find the three biggest values. This can be slower for large arrays.
Searching can never be successfull without sorting ... doing it sequentially will have o(n) complexcity ... however you can use modify merge sort/quick sort algorithm a bit for searching to get logarithmic complexity which is complicated for a starter ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.