Euclidean GCD And LCM On Integers
The Euclidean loop replaces the pair with the remainder until it hits zero, and dividing before multiplying keeps the LCM inside u64 bounds.
Code
fn gcd(mut a: u64, mut b: u64) -> u64 {
// Euclidean algorithm: gcd(a, b) = gcd(b, a mod b)
while b != 0 {
(a, b) = (b, a % b);
}
a
}
fn lcm(a: u64, b: u64) -> u64 {
// divide before multiplying so the product cannot overflow mid-step
a / gcd(a, b) * b
}
fn main() {
println!("gcd(48, 18) = {}", gcd(48, 18));
println!("gcd(17, 5) = {}", gcd(17, 5));
println!("lcm(4, 6) = {}", lcm(4, 6));
println!("lcm(21, 6) = {}", lcm(21, 6));
println!("gcd(0, 7) = {}", gcd(0, 7));
}How the snippet works
Everything happens inside the functions gcd, lcm and main.
The cycling part of this snippet is while b != 0.
What to watch for
- Self-sufficient by design — there is no registry and no lockfile entry.
Applying it
Entry signature: fn gcd(mut a: u64, mut b: u64) -> u64
The run prints labeled output — gcd(48, 18) =, gcd(17, 5) =, lcm(4, 6) = — when the file runs.
main calls 2 helpers in sequence: gcd and lcm.
Statements that set the outcome here
fn gcd(mut a: u64, mut b: u64) -> u64 {
// Euclidean algorithm: gcd(a, b) = gcd(b, a mod b)
while b != 0 {
(a, b) = (b, a % b);
}
a
}
fn lcm(a: u64, b: u64) -> u64 {
// divide before multiplying so the product cannot overflow mid-step
a / gcd(a, b) * 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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- What does Euclidean GCD And LCM On Integers print when run?
- Invoke the file as-is — the `gcd(48, 18) =`, `gcd(17, 5) =`, `lcm(4, 6) =` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.