Scala処理大数

2047 ワード

非常に大きな整数を扱う場合は、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
  }