Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
Scala /
BigInt
Working with big integers is very easy in Python. Let's see how it works in Scala. scala> val x = 1234567890 x: Int = 1234567890 // it's an Int scala> val x: BigInt = 1234567890 // let its type be BigInt x: BigInt = 1234567890 scala> val x = 12345678909 // let's add one more digit <console>:1: error: integer number too large // oops, that scalar is an int val x = 12345678909 ^ scala> val x: BigInt = 12345678909 // let's specify the type <console>:1: error: integer number too large // err, nope val x: BigInt = 12345678909 ^ scala> val x = BigInt("12345678909") // solution: precise it as a string x: scala.math.BigInt = 12345678909 The good news is that once a BigInt is created, you can work with it as if it were a normal integer: scala> val x = BigInt("3473543254343544324") x: scala.math.BigInt = 3473543254343544324 scala> x * x * x res4: scala.math.BigInt = 41910045652080352561414700913973209412657131585450844224 scala> x.pow(3) res5: scala.math.BigInt = 41910045652080352561414700913973209412657131585450844224 scala> x + 2 res6: scala.math.BigInt = 3473543254343544326 scala> x > 42 res7: Boolean = true See also BigInt and BigDecimal. Generate big random primesGenerate a random prime with 100 bits: scala> BigInt.probablePrime(100, scala.util.Random) res9: scala.math.BigInt = 967064563528666024098824241151 Further examples// how much is 2^1024 scala> BigInt(2).pow(1024) res2: scala.math.BigInt = 1797693134862315907729305190789024733617976978942306572734 300811577326758055009631327084773224075360211201138798713933576587897688144166224928 474306394741243777678934248654852763022196012460941194530829520850057688381506823424 62881473913110540827237163350510684586298239947245938479716304835356329624224137216 // this example is from the book "Scala for the Impatient": // "One way to create random file or directory names is to produce a random BigInt and // convert it to base36." scala> BigInt(100, scala.util.Random) res3: scala.math.BigInt = 777764365538802043588777462195 // random BigInt with 100 bits scala> BigInt(100, scala.util.Random).toString(36) // converted to base 36 res4: String = o79zx6lqjanmsqqbllg // here is the random string |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |