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.
Code
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
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.
FAQ
- What does GCD And LCM With big.Int print when run?
- The script runs standalone; its 3 labeled outputs include `gcd:`, `lcm:`, `reduced:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.