Go: Quotient and remainder

Returning more than one value is a Go habit: the extra value often says whether the call worked.

What to build

A program that divides pairs of numbers using a function with several results.

Requirements

  • Write a function divmod(a, b int) (q, r int, ok bool) where ok is false when b is 0.
  • Read n, then n pairs a b. For each pair print a = q * b + r with the real numbers, or a / 0 is undefined when b is 0.

Input

Line 1: n. Then n lines a b.

Output

n lines.

Constraints

1 ≤ n ≤ 30; a is between 0 and 100000 and b between 0 and 1000.

Example

Input:

3
17 5
10 0
6 3

Output:

17 = 3 * 5 + 2
10 / 0 is undefined
6 = 2 * 3 + 0

Why it works

The function returns the quotient, the remainder and a flag. The caller checks the flag first, so it never divides by zero.

Examples

Example 1 · Input
3
17 5
10 0
6 3
Expected output
17 = 3 * 5 + 2
10 / 0 is undefined
6 = 2 * 3 + 0
Example 2 · Input
2
0 7
99 100
Expected output
0 = 0 * 7 + 0
99 = 0 * 100 + 99

Hints

Hint 1

Write func divmod(a, b int) (int, int, bool) where the bool says whether b is not zero.

Hint 2

Check the bool before printing.

Solution

Show one correct solution (try it yourself first)
package main

import "fmt"

func divmod(a, b int) (q, r int, ok bool) {
	if b == 0 {
		return 0, 0, false
	}
	return a / b, a % b, true
}

func main() {
	var n int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		var a, b int
		fmt.Scan(&a, &b)
		q, r, ok := divmod(a, b)
		if !ok {
			fmt.Printf("%d / 0 is undefined\n", a)
		} else {
			fmt.Printf("%d = %d * %d + %d\n", a, q, b, r)
		}
	}
}

▶ Open this solution in the compiler

Lesson: Functions and multiple return values →