Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division with returning quotient and remainder

Tags:

go

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.

like image 592
vildhjarta Avatar asked May 12 '17 20:05

vildhjarta


People also ask

How do you divide quotient and remainder?

The dividend divisor quotient remainder formula can be applied if we know either the dividend or remainder or divisor. 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.

Which function will return the quotient and remainder on division of numerator with denominator?

Description. The div() function calculates the quotient and remainder of the division of numerator by denominator.

What is remainder and quotient in division with example?

The remainder is always less than the divisor. If the remainder is greater than the divisor, it means that the division is incomplete. It can be greater than or lesser than the quotient. For example; when 41 is divided by 7, the quotient is 5 and the remainder is 6. Here the remainder is greater than the quotient.

How do you find quotient and remainder using division algorithm?

When we divide a positive integer (the dividend) by another positive integer (the divisor), we obtain a quotient. We multiply the quotient to the divisor, and subtract the product from the dividend to obtain the remainder. Such a division produces two results: a quotient and a remainder.


2 Answers

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)

like image 73
Kaedys Avatar answered Oct 22 '22 14:10

Kaedys


if you want a one-liner,

quotient, remainder := numerator/denominator, numerator%denominator
like image 45
carusyte Avatar answered Oct 22 '22 13:10

carusyte