Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigInteger in Kotlin

I need to make use of BigInteger but can't find anything similar in kotlin.

Is there any alternative class in kotlin to BigInteger of java?

or

should I import java class into kotlin?

like image 454
Akshar Patel Avatar asked May 31 '17 14:05

Akshar Patel


People also ask

What is BigInteger used for?

BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java. lang. Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

What is BigInteger and BigDecimal?

the BigInteger class allows representation of and calculations on arbitrarily large integers (whole numbers); the BigDecimal class allows precise representation of any real number that can be represented precisely in decimal notation, and allows calculations on non-integers with arbitrary precision.

What is the difference between BigInteger and integer?

The int data type is the primary integer data type in SQL Server. The bigint data type is intended for use when integer values might exceed the range that is supported by the int data type. bigint fits between smallmoney and int in the data type precedence chart.


2 Answers

You can use any of the built-in Java classes from Kotlin, and you should. They'll all work the exact same way as they do in Java. Kotlin makes a point of using what the Java platform has to offer instead of re-implementing them; for example, there are no Kotlin specific collections, just some interfaces on top of Java collections, and the standard library uses those collections as well.

So yes, you should just use java.math.BigInteger. As a bonus, you'll actually be able to use operators instead of function calls when you use BigInteger from Kotlin: + instead of add, - instead of subtract, etc.

like image 38
zsmb13 Avatar answered Sep 28 '22 10:09

zsmb13


java.math.BigInteger can be used in Kotlin as any other Java class. There are even helpers in stdlib that make common operations easier to read and write. You can even extend the helpers yourself to achieve greater readability:

import java.math.BigInteger

fun Long.toBigInteger() = BigInteger.valueOf(this)
fun Int.toBigInteger() = BigInteger.valueOf(toLong())

val a = BigInteger("1")
val b = 12.toBigInteger()
val c = 2L.toBigInteger()

fun main(argv:Array<String>){
    println((a + b)/c) // prints out 6
}
like image 163
miensol Avatar answered Sep 28 '22 08:09

miensol