Course / The terminal and the language
Quotient and remainder
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach lab: download it, edit the file named in the instructions, then submit.
gonomicon fetch week-1/12-03-divide-with-remainder
cd 12-03-divide-with-remainder
gonomicon submitGoal
Fill in DivMod so it returns both the whole-number quotient and the remainder of a divided by b, and returns 0, 0 when b is 0.
Example
q, r := DivMod(17, 5)
fmt.Println(q, r) // 3 2
q, r = DivMod(3, 7)
fmt.Println(q, r) // 0 3
q, r = DivMod(10, 0)
fmt.Println(q, r) // 0 0
17 / 5 is 3 and 17 % 5 is the leftover 2. When a is smaller than b, the quotient is 0 and the remainder is a itself.
Go's division throws away the fraction (it truncates toward zero), so DivMod(-7, 2) gives -3 -1. Just use / and % and Go does the right thing.
Rules
- Edit
divmod.go. The function has a// TODOcomment and areturnline you will change. - Return the quotient first, then the remainder, as two values:
return x, y. - Dividing by zero crashes a Go program, so check for
b == 0before you divide. - Do not change the line
func DivMod(a, b int) (int, int) {. Do not add imports.
What you'll practice
Returning two values from one function, and guarding a risky operation with an early return.
Run it
gonomicon fetch week-1/12-03-divide-with-remainder
cd 12-03-divide-with-remainder
gonomicon test
gonomicon submit
Hints
- The function hands back two values, so it needs
return x, ywith a comma. Division by zero crashes a Go program, so checkbfirst. a / bgives the whole-number quotient anda % bgives the remainder. Whenb == 0, return0, 0before dividing.if b == 0 { return 0, 0 }thenreturn a / b, a % b.