Scala处理大数

如果要处理一个非常大的整数,可以使用Scala的BigInt或者BigDecimal,eg.

    val a = BigDecimal(123456789.02)
    println(a)
    println(a + a)

    val b = BigInt(1234567890)
    println(b + b)

    val c = BigDecimal(12345678900000000000000.0)
    println(c)
    println(c + c)

输出如下:

123456789.02
246913578.04
2469135780
1.23456789E+22
2.46913578E+22

在BigDecimal.scala中实现了+ - * /等基本类型的运算,如下:

/** Addition of BigDecimals
   */
  def +  (that: BigDecimal): BigDecimal = new BigDecimal(this.bigDecimal add that.bigDecimal, mc)

  /** Subtraction of BigDecimals
   */
  def -  (that: BigDecimal): BigDecimal = new BigDecimal(this.bigDecimal subtract that.bigDecimal, mc)

  /** Multiplication of BigDecimals
   */
  def *  (that: BigDecimal): BigDecimal = new BigDecimal(this.bigDecimal.multiply(that.bigDecimal, mc), mc)

  /** Division of BigDecimals
   */
  def /  (that: BigDecimal): BigDecimal = new BigDecimal(this.bigDecimal.divide(that.bigDecimal, mc), mc)

  /** Division and Remainder - returns tuple containing the result of
   *  divideToIntegralValue and the remainder.  The computation is exact: no rounding is applied.
   */
  def /% (that: BigDecimal): (BigDecimal, BigDecimal) =
    this.bigDecimal.divideAndRemainder(that.bigDecimal) match {
      case Array(q, r)  => (new BigDecimal(q, mc), new BigDecimal(r, mc))
    }

  /** Divide to Integral value.
   */
  def quot (that: BigDecimal): BigDecimal =
    new BigDecimal(this.bigDecimal divideToIntegralValue that.bigDecimal, mc)

  /** Returns the minimum of this and that, or this if the two are equal
   */
  def min (that: BigDecimal): BigDecimal = (this compare that) match {
    case x if x <= 0 => this
    case _           => that
  }

  /** Returns the maximum of this and that, or this if the two are equal
   */
  def max (that: BigDecimal): BigDecimal = (this compare that) match {
    case x if x >= 0 => this
    case _           => that
  }

你可能感兴趣的:(Scala处理大数)