GCD And LCM With big.Int

Compute GCD and LCM with math/big.Int so values beyond int64 never overflow, and reduce fractions by dividing out the common divisor.

GoData Integrity

Code

gosnippet
29 lines
package main

import (
	"fmt"
	"math/big"
)

func lcm(a, b *big.Int) *big.Int {
	// LCM(a,b) = a*b / GCD(a,b):先除后乘避免中间值膨胀
	g := new(big.Int).GCD(nil, nil, a, b)
	q := new(big.Int).Quo(a, g)
	return new(big.Int).Mul(q, b)
}

func main() {
	a := big.NewInt(1071)
	b := big.NewInt(462)

	g := new(big.Int).GCD(nil, nil, a, b)
	fmt.Println("gcd:", g)

	fmt.Println("lcm:", lcm(a, b))

	// 约分分数:分子分母同除 GCD
	num := big.NewInt(1071)
	den := big.NewInt(462)
	d := new(big.Int).GCD(nil, nil, num, den)
	fmt.Println("reduced:", new(big.Int).Quo(num, d), "/", new(big.Int).Quo(den, d))
}

Reading the snippet

All the substantive work belongs to the functions lcm and main — everything else is wiring.

What to watch for

  • Zero third-party dependencies — the runtime provides every API used here.

Using it

Signature: func lcm(a, b *big.Int) *big.Int

The demo output is labeled (gcd:, lcm:, reduced:), so every printed line maps back to its originating operation.

Running the file executes main, which drives lcm in order.

Key statements

func lcm(a, b *big.Int) *big.Int {
	// LCM(a,b) = a*b / GCD(a,b):先除后乘避免中间值膨胀
	g := new(big.Int).GCD(nil, nil, a, b)
	q := new(big.Int).Quo(a, g)
	return new(big.Int).Mul(q, b)
}

Interactive Tools for This Topic

FAQ

What does GCD And LCM With big.Int print when run?
The script runs standalone; its 3 labeled outputs include `gcd:`, `lcm:`, `reduced:`.