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?
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.
You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.
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.
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);
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With