Division with returning quotient and remainder

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)
}
  • https://golang.org/pkg/math/bits#Div
  • https://golang.org/pkg/math/bits#Div32
  • https://golang.org/pkg/math/bits#Div64

Integer division plus modulus accomplishes this.

func divmod(numerator, denominator int64) (quotient, remainder int64) {
    quotient = numerator / denominator // integer division, decimals are truncated
    remainder = numerator % denominator
    return
}

https://play.golang.org/p/rimqraYE2B

Edit: Definitions

Quotient, in the context of integer division, is the number of whole times the numerator goes into the denominator. In other words, it is identical to the decimal statement: FLOOR(n/d)

Modulo gives you the remainder of such a division. The modulus of a numerator and denominator will always be between 0 and d-1 (where d is the denominator)


if you want a one-liner,

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

Tags:

Go