Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 298
Valentin Tihomirov Avatar asked Dec 05 '15 10:12

Valentin Tihomirov


People also ask

Which operator gives remainder and quotient?

The division operator / computes the quotient (either between float or integer variables). The modulus operator % computes the remainder when one integer is divided by another (modulus operator cannot be used for floating-type variables).

Can remainder and quotient be same?

Explanation: When 8 is divided by 3 and 7, it returns the same Quotient and Remainder. 8 / 3 = 8 % 3, 8 / 7 = 8 % 7.

How do you divide quotient and remainder?

The formula can be applied accordingly. For dividend, the formula is: Dividend = Divisor × Quotient + Remainder. For divisor, the formula is: Dividend/Divisor = Quotient + Remainder/Divisor.


3 Answers

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

import scala.math.Integral.Implicits._

val (quotient, remainder) = 5 /% 2
like image 54
Morgen Avatar answered Oct 17 '22 06:10

Morgen


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.

like image 25
elm Avatar answered Oct 17 '22 06:10

elm


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)
}
like image 26
Alexey Romanov Avatar answered Oct 17 '22 07:10

Alexey Romanov