Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java/Scala BigInteger Pasting

I have a problem with the Java BigInteger class: I can't paste a large value into BigInteger. For example, let's say I want to assign a BigInteger to this number:

26525285981219105863630848482795

I cannot assign it directly, because the compiler thinks it's an integer:

val bi = 26525285981219105863630848482795 //compile error

But I want it to be a BigInteger. Is there any way to be able to directly paste this into the source code?

If there is no such way, then is there a way in Scala, which has a much easier to use BigInt class?

like image 863
Michael Dickens Avatar asked Nov 06 '09 18:11

Michael Dickens


3 Answers

Starting in Scala 3, and improvements brought to numeric literals, you can use the following form:

val big: BigInt = 26525285981219105863630848482795
// 26525285981219105863630848482795

or even:

val big: BigInt = 26_525_285_981_219_105_863_630_848_482_795
// 26525285981219105863630848482795
like image 118
Xavier Guihot Avatar answered Nov 06 '22 04:11

Xavier Guihot


rtperson's answer is correct from a Java perspective, but in Scala you can do more with scala.BigInts than what you can do with java.math.BigIntegers.

For example:

scala> val a = new BigInteger("26525285981219105863630848482795");
a: java.math.BigInteger = 26525285981219105863630848482795

scala> a + a
:7: error: type mismatch;
found   : java.math.BigInteger
required: String
       a + a

The canonical way in Scala to instantiate a class is to use a factory located in the companion object. When you write Foo(args) in Scala, this is translated to Foo.apply(args), where Foo is a singleton object - the companion object. So to find the ways of constructing BigInts you could have a look at the BigInt object in the Scala library, and specifically at its apply construct.

So, three ways of constructing an BigInt are: passing it an Int, a Long or a String to parse. Example:

scala> val x = BigInt(12)
x: BigInt = 12

scala> val y = BigInt(12331453151315353L)
y: BigInt = 12331453151315353

scala> val z = BigInt("12124120474210912741099712094127124112432")
z: BigInt = 12124120474210912741099712094127124112432

scala> x + y * z
res1: BigInt = 149508023628635151923723925873960750738836935643459768508

Note the nice thing that you can do natural looking arithmetic operations with a BigInt, which is not possible with a BigInteger !

like image 29
Flaviu Cipcigan Avatar answered Nov 06 '22 05:11

Flaviu Cipcigan


This should work:

BigInteger bigInt = new BigInteger("26525285981219105863630848482795");

BigInteger reads strings and parses them into the correct number. Because of this, you'll want to check out java.text.NumberFormat.

like image 42
rtperson Avatar answered Nov 06 '22 04:11

rtperson