Division with returning quotient and remainder

Viewed 35134

I try to migrate from Python to Golang. I currently do research some math operations and wonder about how can I get both quotient and remainder value with result of a division. I'm going to share below an equivalent of Python code.

hours, remainder = divmod(5566, 3600)
minutes, seconds = divmod(remainder, 60)
print('%s:%s' % (minutes, seconds))
# 32:46

Above will be my aim. Thanks.

4 Answers

if you want a one-liner,

quotient, remainder := numerator/denominator, numerator%denominator

If you have a 32 bit number, you can use one of these:

package main
import "math/bits"

func main() {
   { // example 1
      var n uint = 4294967295
      q, r := bits.Div(0, n, 2)
      println(q == n / 2, r == 1)
   }
   { // example 2
      var n uint32 = 4294967295
      q, r := bits.Div32(0, n, 2)
      println(q == n / 2, r == 1)
   }
}

If you have a 64 bit number, you can do it like this:

package main
import "math/bits"

func main() {
   var n uint64 = 18446744073709551615
   q, r := bits.Div64(0, n, 2)
   println(q == n / 2, r == 1)
}

If you have something larger than 64 bit, you can do it like this:

package main
import "math/bits"

func main() {
   q, r := bits.Div64(1, 0, 2)
   println(q == 9223372036854775808, r == 0)
}

I did this function maybe it's what you are looking for.

//QuotientAndRemainderF32 Computes the integer quotient and the remainder of the inputs. This function rounds floor(x/y) to the nearest integer towards -inf.
func QuotientAndRemainderF32(x, y float32) (Remainder, Quotient float32) {
    Quotient = float32(math.Floor(float64(x / y)))
    Remainder = x - y*Quotient
    return Remainder, Quotient
}
Related