Course outline
Course / The terminal and the language

Quotient and remainder

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each 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 submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

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 // TODO comment and a return line 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 == 0 before 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

  1. The function hands back two values, so it needs return x, y with a comma. Division by zero crashes a Go program, so check b first.
  2. a / b gives the whole-number quotient and a % b gives the remainder. When b == 0, return 0, 0 before dividing.
  3. if b == 0 { return 0, 0 } then return a / b, a % b.

Something wrong with this lesson? Report a problem