Search code examples
go

Division with returning quotient and remainder


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.


Solution

  • 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)