Is there a separation operation that produces both a factor and a reminder?

I'm currently writing some kind of ugly code like

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

Is it listed in the standard library?

+4
source share
4 answers

No (except BigIntas indicated 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 increase productivity by creating separate classes for each type, for example

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

In BigIntnote the operation /%that supplies the pair with division and reminder (see API ). Pay attention, for example,

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)

Int BigInt.

+5

A bit late in the game, but with Scala 2.8 this works:

import scala.math.Integral.Implicits._

val (quotient, remainder) = 5 /% 2
+5
source

BigInt does it

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

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

0
source

Source: https://habr.com/ru/post/1618691/


All Articles