How to assign a very large number to BigInteger?
Asked Answered
H

4

9

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?

Hawaiian answered 20/6, 2015 at 17:9 Comment(0)
A
9

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);
Athalia answered 20/6, 2015 at 17:10 Comment(0)
P
3

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
}
Perfusion answered 20/6, 2015 at 17:22 Comment(0)
B
1

Use the String contructor: http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger(java.lang.String)

      public BigInteger(String val)
Bikales answered 20/6, 2015 at 17:11 Comment(0)
D
0

Use the string constructor.

Like this.

http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger(java.lang.String)

If the long datatype could handle arbitrarily large numbers, there would be no need for a BigInteger.

Detach answered 20/6, 2015 at 17:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.