Is there a division operation that produces both quotient and reminder?

跟風遠走 提交于 2020-01-11 04:52:05

问题


Currently I write some ugly code like

    def div(dividend: Int, divisor: Int) = {
        val q = dividend / divisor
        val mod = dividend % divisor
        (q, mod)
    } 

Is it specified in standard library?


回答1:


No (except for BigInt, as mentioned in other answers), but you can add it:

implicit class QuotRem[T: Integral](x: T) {
  def /%(y: T) = (x / y, x % y)
}

will work for all integral types. You can improve performance by making separate classes for each type such as

implicit class QuotRemInt(x: Int) extends AnyVal {
  def /%(y: Int) = (x / y, x % y)
}



回答2:


A bit late to the game, but since Scala 2.8 this works:

import scala.math.Integral.Implicits._

val (quotient, remainder) = 5 /% 2



回答3:


In BigInt, note /% operation which delivers a pair with the division and the reminder (see API). Note for instance

scala> BigInt(3) /% BigInt(2)
(scala.math.BigInt, scala.math.BigInt) = (1,1)

scala> BigInt(3) /% 2
(scala.math.BigInt, scala.math.BigInt) = (1,1)

where the second example involves an implicit conversion from Int to BigInt.




回答4:


BigInt does it

def /%(that: BigInt): (BigInt, BigInt)

Division and Remainder - returns tuple containing the result of divideToIntegralValue and the remainder.



来源:https://stackoverflow.com/questions/34104009/is-there-a-division-operation-that-produces-both-quotient-and-reminder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!