Go: GCD and LCM

Recursion expresses Euclid's ancient algorithm in two lines.

What to build

A program that finds the greatest common divisor and the least common multiple of pairs of numbers.

Requirements

  • Write a recursive function gcd(a, b int64) int64 and a function lcm(a, b int64) int64 that uses it.
  • Read n, then n pairs a b. For each pair print gcd G lcm L and, if G is 1, add coprime at the end.

Input

Line 1: n. Then n lines a b.

Output

n lines.

Constraints

1 ≤ n ≤ 30; 1 ≤ a, b ≤ 1000000.

Example

Input:

3
12 18
7 13
100 75

Output:

gcd 6 lcm 36
gcd 1 lcm 91 coprime
gcd 25 lcm 300

Why it works

Euclid's rule replaces (a, b) with (b, a % b) until the second number is 0. Dividing by the gcd before multiplying keeps the lcm as small as possible, and int64 holds the result of up to 10^12.

Examples

Example 1 · Input
3
12 18
7 13
100 75
Expected output
gcd 6 lcm 36
gcd 1 lcm 91 coprime
gcd 25 lcm 300
Example 2 · Input
2
5 5
1 1000000
Expected output
gcd 5 lcm 5
gcd 1 lcm 1000000 coprime

Hints

Hint 1

The greatest common divisor: gcd(a, 0) is a, otherwise gcd(b, a % b). Write it as a recursive function.

Hint 2

lcm = a / gcd * b; use int64 because the result can be large.

Solution

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

import "fmt"

func gcd(a, b int64) int64 {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func lcm(a, b int64) int64 {
	return a / gcd(a, b) * b
}

func main() {
	var n int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		var a, b int64
		fmt.Scan(&a, &b)
		g := gcd(a, b)
		if g == 1 {
			fmt.Printf("gcd %d lcm %d coprime\n", g, lcm(a, b))
		} else {
			fmt.Printf("gcd %d lcm %d\n", g, lcm(a, b))
		}
	}
}

▶ Open this solution in the compiler

Lesson: Functions and multiple return values →