Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a very large number to BigInteger?

Given the following input:

4534534534564657652349234230947234723947234234823048230957349573209483057
12324000123123

I have attempted to assign these values to BigInteger in the following way.

public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        BigInteger num1 = BigInteger.valueOf(sc.nextLong());
        sc.nextLine();
        BigInteger num2 = BigInteger.valueOf(sc.nextLong());

        BigInteger additionTotal = num1.add(num2);
        BigInteger multiplyTotal = num1.multiply(num2);

        System.out.println(additionTotal);
        System.out.println(multiplyTotal);
    }

The first value is outside of the boundaries for a Long number, and so I get the following exception:

Exception in thread "main" java.util.InputMismatchException: For input string: "4534534534564657652349234230947234723947234234823048230957349573209483057"

I assumed that BigInteger expects a Long type for use with valueOf() method (as stated here). How can I pass extremely large numbers to BigInteger?

like image 490
crmepham Avatar asked Jun 20 '15 17:06

crmepham


People also ask

How big can BigInteger get?

The BigInteger class allows you to create and manipulate integer numbers of any size. The BigInteger class stores a number as an array of unsigned, 32-bit integer "digits" with a radix, or base, of 4294967296.

How do you represent a large number in Java?

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.

How do I change BigInteger to long?

longValue() converts this BigInteger to a long. This conversion is analogous to a narrowing primitive conversion from long to int. If this BigInteger is too big to fit in a long, only the low-order 64 bits are returned.


2 Answers

When the input number does not fit in long, use the constructor that takes a String argument:

String numStr = "453453453456465765234923423094723472394723423482304823095734957320948305712324000123123";
BigInteger num = new BigInteger(numStr);
like image 153
Sergey Kalinichenko Avatar answered Sep 30 '22 12:09

Sergey Kalinichenko


Read the huge number in as a String.

public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    String s = in.nextLine();
    BigInteger num1 = new BigInteger(s);

    s = in.nextLine();
    BigInteger num2 = new BigInteger(s);

    //do stuff with num1 and num2 here
}
like image 31
Adam Evans Avatar answered Sep 30 '22 14:09

Adam Evans