Taskintro
Compute the greatest common divisor
Also called gcd, greatest common factor, highest common factor, lcm, least common multiple, Euclid's algorithm, math.gcd, math.lcm, std::gcd, std::lcm, BigInteger.gcd.
Compute the greatest common divisor and the least common multiple of two integers with Euclid's algorithm or a library function, with negative numbers and zero.
- Evidence
- Code in 10 languages
Task
Compute the greatest common divisor and the least common multiple of two integers.
- The greatest common divisor (GCD) "is the largest natural number that divides both a and b without leaving a remainder"1. Rosetta Code says that it "is also known as greatest common factor (gcf) and greatest common measure"2.
- The least common multiple (LCM) "is the smallest positive integer that has both m and n as factors"3.
The function gcd_and_lcm(a, b) returns the pair (gcd, lcm). For example, gcd_and_lcm(12, 18) is (6, 36). Both results are never negative, so gcd_and_lcm(-12, 18) is (6, 36) too.
Zero needs a rule. Each integer divides 0, so the GCD of 0 and 7 is 7, and the GCD of 0 and 0 is 0 by convention. For the LCM, "if either m or n is zero, then the least common multiple is zero"3.
The items are 64-bit signed integers. Neither is the smallest 64-bit value, because its absolute value does not fit, and the LCM fits in 64 bits.
Euclid's algorithm finds the GCD with a loop. It "is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number"1. The remainder of a division does the same as many subtractions, so the loop is:
- If
bis 0, the answer isa. - Otherwise, replace the pair
(a, b)with(b, a mod b), and go to step 1.
For 48 and 180, the pairs are (48, 180), (180, 48), (48, 36), (36, 12) and (12, 0), so the GCD is 12. The LCM then follows from the GCD: it is the absolute value of a / gcd * b.
Solutions
| Language | GCD | LCM |
|---|---|---|
| Python | math.gcd(a, b) |
math.lcm(a, b) |
| JavaScript, TypeScript | Euclid's algorithm with BigInt values |
a / g * b |
| Java | Euclid's algorithm; BigInteger.gcd for big numbers |
a / g * b |
| C# | Euclid's algorithm; BigInteger.GreatestCommonDivisor for big numbers |
a / g * b |
| Go | Euclid's algorithm; big.Int.GCD for big numbers |
a / g * b |
| Rust | Euclid's algorithm on u64 values |
a / g * b |
| C | Euclid's algorithm with llabs |
a / g * b |
| C++ | std::gcd(a, b) |
std::lcm(a, b) |
| Bash | Euclid's algorithm with $((a % b)) |
$((a / g * b)) |
- Python.
math.gcdandmath.lcmtake any count of integers. If any argument is nonzero, "the returned value is the largest positive integer that is a divisor of all arguments. If all arguments are zero, then the returned value is 0"4. For the LCM, "If any of the arguments is zero, then the returned value is 0"4. Python integers have no size limit. - JavaScript. There is no GCD function. The solution uses
BigIntvalues, because anumbercannot hold each 64-bit integer, and computes the absolute values withx < 0n ? -x : x. - TypeScript. The same code as JavaScript, with the type
bigint. - Java. There is no GCD function for
longvalues.BigInteger.gcd"Returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val). Returns 0 if this == 0 && val == 0"5. The solution usesMath.absExact, which throws an exception for the smallestlongvalue6. - C#. There is no GCD function for
longvalues. ForBigInteger, "If either parameter is zero, the method returns the absolute value of the non-zero parameter. If both values are zero, the method returns zero"7.Math.AbsthrowsOverflowExceptionforlong.MinValue. - Go. There is no GCD function for
int64values.GCDofbig.Int"sets z to the greatest common divisor of a and b and returns z", and "a and b may be positive, zero or negative"8. - Rust. The standard library has no GCD function. The solution takes
unsigned_absof each value, so the loop works onu64values with no sign. - C. The solution uses a loop with
long longvalues andllabsfrom<stdlib.h>. - C++.
std::gcdis in<numeric>. "If both m and n are zero, returns zero. Otherwise, returns the greatest common divisor of |m| and |n|"9.std::lcmis in the same header: "If either m or n is zero, returns zero. Otherwise, returns the least common multiple of |m| and |n|"10. - Bash. The solution uses a
whileloop with$((a % b)), and prints the GCD and the LCM on one line.
The Python functions:
import math
print(math.gcd(12, 18), math.lcm(12, 18))
print(math.gcd(-12, 18), math.lcm(-12, 18))
print(math.gcd(0, 7), math.gcd(0, 0), math.lcm(0, 7))
print(math.gcd(12, 18, 30), math.lcm(4, 6, 10))
6 36
6 36
7 0 0
6 60
The C++ functions:
#include <iostream>
#include <numeric>
int main() {
std::cout << std::gcd(12, 18) << ' ' << std::lcm(12, 18) << '\n';
std::cout << std::gcd(-12, 18) << ' ' << std::lcm(-12, 18) << '\n';
std::cout << std::gcd(0, 0) << '\n';
}
6 36
6 36
0
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
common-factor,coprimeandeuclid-example: two numbers with a common factor, and two numbers with no common factor.zero-and-number: the GCD of 0 and 7 is 7, and the LCM is 0.both-zero: the GCD and the LCM of 0 and 0 are 0.negativeandboth-negative: the results are not negative.equal: the GCD and the LCM of a number and itself are the number.one: the GCD of 1 and a number is 1.multiple: whenadividesb, the GCD isaand the LCM isb.fibonacci: 832040 and 514229 are consecutive Fibonacci numbers. They are the worst case for Euclid's algorithm, and the loop takes 28 steps. "This result suffices to show that the number of steps in Euclid's algorithm can never be more than five times the number of its digits (base 10)"1.big-lcm: the LCM of 3000000000000000000 and 6000000000000000000 fits in 64 bits, but their product does not.largest: the largest 64-bit value and its negation.
Pitfalls
- The remainder can be negative. In Go, Java, C, C++, C#, JavaScript and Bash, the remainder has the sign of the dividend. In Go,
x / yis "truncated towards zero"11. So Euclid's algorithm without the absolute values gives a negative GCD for some inputs. Take the absolute values first. See Integer division and modulo:
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
func gcd(a, b int64) int64 {
for b != 0 {
a, b = b, a%b
}
return a
}
func main() {
fmt.Println(gcd(12, -18), gcd(-12, 18))
}
-6 6
In Python, the result of % has the sign of the divisor, so the same loop gives other signs. math.gcd is never negative.
- The LCM overflows in the product.
a * b / gcdcomputes the product first, and the product of two large numbers does not fit, with no error. Divide first:a / gcd * b. The division is exact, because the GCD dividesa:
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
func main() {
a, b, g := int64(3000000000000000000), int64(6000000000000000000), int64(3000000000000000000)
fmt.Println(a * b / g)
fmt.Println(a / g * b)
}
-2
6000000000000000000
- The absolute value of the smallest integer. The smallest 64-bit value is -9223372036854775808, and 9223372036854775808 does not fit. In Java, for
Long.MIN_VALUE"the result is that same value, which is negative. In contrast, the absExact(long) method throws an ArithmeticException for this value"6:
This code runs but gives a wrong answer on purpose.
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(Long.MIN_VALUE));
try {
System.out.println(Math.absExact(Long.MIN_VALUE));
} catch (ArithmeticException e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
-9223372036854775808
ArithmeticException
The GCD of the smallest value and 0 is 9223372036854775808, which does not fit either. For std::gcd in C++, "If either |m| or |n| is not representable as a value of type std::common_type_t<M, N>, the behavior is undefined"9. Use big integers when the inputs can be this value. See Use big integers.
- The subtraction form is slow. Euclid's original form subtracts the smaller number from the larger number. For 1000000007 and 1, it takes a billion subtractions. The remainder form takes one step.
Related tasks
- Check whether a number is prime: two numbers are coprime when their GCD is 1.
- Compute Fibonacci numbers: consecutive Fibonacci numbers are the worst case of Euclid's algorithm.
- Sum and multiply a list: the GCD and the LCM of a list are reductions with these functions.
- Use big integers: the GCD of integers with no size limit.
The algorithms are on the algorithm site: the Euclidean algorithm and the binary GCD algorithm.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
import math
def gcd_and_lcm(a: int, b: int) -> tuple[int, int]:
"""Return the greatest common divisor and the least common multiple."""
return math.gcd(a, b), math.lcm(a, b)
def gcd_and_lcm_euclid(a: int, b: int) -> tuple[int, int]:
"""Return the same pair with Euclid's algorithm."""
x, y = abs(a), abs(b)
while y != 0:
x, y = y, x % y
lcm = 0 if a == 0 or b == 0 else abs(a) // x * abs(b)
return x, lcm
test_gcd.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
import pytest
from gcd import gcd_and_lcm, gcd_and_lcm_euclid
CASES = [
("common-factor", 12, 18, (6, 36)),
("coprime", 17, 5, (1, 85)),
("euclid-example", 48, 180, (12, 720)),
("zero-and-number", 0, 7, (7, 0)),
("both-zero", 0, 0, (0, 0)),
("negative", -12, 18, (6, 36)),
("both-negative", -4, -6, (2, 12)),
("equal", 9, 9, (9, 9)),
("one", 1, 1000000007, (1, 1000000007)),
("multiple", 5, 25, (5, 25)),
("fibonacci", 832040, 514229, (1, 427859097160)),
("big-lcm", 3000000000000000000, 6000000000000000000, (3000000000000000000, 6000000000000000000)),
("largest", 9223372036854775807, -9223372036854775807, (9223372036854775807, 9223372036854775807)),
]
@pytest.mark.parametrize(("name", "a", "b", "want"), CASES, ids=[c[0] for c in CASES])
def test_gcd_and_lcm(name, a, b, want):
assert gcd_and_lcm(a, b) == want
assert gcd_and_lcm_euclid(a, b) == want
assert gcd_and_lcm(b, a) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
#ifndef GCD_AND_LCM_HPP
#define GCD_AND_LCM_HPP
#include <numeric>
#include <utility>
// Returns the greatest common divisor and the least common multiple of a and
// b. std::gcd and std::lcm have undefined behavior when a result does not
// fit, so neither a nor b can be LLONG_MIN.
inline std::pair<long long, long long> gcd_and_lcm(long long a, long long b) {
return {std::gcd(a, b), std::lcm(a, b)};
}
#endif
test_gcd.cpp 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
#include <cstdio>
#include "gcd.hpp"
namespace {
struct test_case {
const char* name;
long long a, b, gcd, lcm;
};
const test_case cases[] = {
{"common-factor", 12, 18, 6, 36},
{"coprime", 17, 5, 1, 85},
{"euclid-example", 48, 180, 12, 720},
{"zero-and-number", 0, 7, 7, 0},
{"both-zero", 0, 0, 0, 0},
{"negative", -12, 18, 6, 36},
{"both-negative", -4, -6, 2, 12},
{"equal", 9, 9, 9, 9},
{"one", 1, 1000000007, 1, 1000000007},
{"multiple", 5, 25, 5, 25},
{"fibonacci", 832040, 514229, 1, 427859097160LL},
{"big-lcm", 3000000000000000000LL, 6000000000000000000LL, 3000000000000000000LL, 6000000000000000000LL},
{"largest", 9223372036854775807LL, -9223372036854775807LL, 9223372036854775807LL, 9223372036854775807LL},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
const auto want = std::pair{c.gcd, c.lcm};
if (gcd_and_lcm(c.a, c.b) != want || gcd_and_lcm(c.b, c.a) != want) {
std::printf("FAIL %s\n", c.name);
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
/** The greatest common divisor and the least common multiple of two long values. */
public final class Gcd {
private Gcd() {}
/** Returns {gcd, lcm}. absExact throws ArithmeticException for Long.MIN_VALUE. */
public static long[] gcdAndLcm(long a, long b) {
long x = Math.absExact(a);
long y = Math.absExact(b);
while (y != 0) {
long r = x % y;
x = y;
y = r;
}
long lcm = a == 0 || b == 0 ? 0 : Math.multiplyExact(Math.abs(a) / x, Math.abs(b));
return new long[] {x, lcm};
}
}
GcdTest.java 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigInteger;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class GcdTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("common-factor", 12, 18, 6, 36),
Arguments.of("coprime", 17, 5, 1, 85),
Arguments.of("euclid-example", 48, 180, 12, 720),
Arguments.of("zero-and-number", 0, 7, 7, 0),
Arguments.of("both-zero", 0, 0, 0, 0),
Arguments.of("negative", -12, 18, 6, 36),
Arguments.of("both-negative", -4, -6, 2, 12),
Arguments.of("equal", 9, 9, 9, 9),
Arguments.of("one", 1, 1000000007, 1, 1000000007),
Arguments.of("multiple", 5, 25, 5, 25),
Arguments.of("fibonacci", 832040, 514229, 1, 427859097160L),
Arguments.of("big-lcm", 3000000000000000000L, 6000000000000000000L, 3000000000000000000L, 6000000000000000000L),
Arguments.of("largest", 9223372036854775807L, -9223372036854775807L, 9223372036854775807L, 9223372036854775807L)
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void gcdAndLcm(String name, long a, long b, long gcd, long lcm) {
assertArrayEquals(new long[] {gcd, lcm}, Gcd.gcdAndLcm(a, b));
assertArrayEquals(new long[] {gcd, lcm}, Gcd.gcdAndLcm(b, a));
assertEquals(gcd, BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValueExact());
}
@Test
void smallestValueThrows() {
assertThrows(ArithmeticException.class, () -> Gcd.gcdAndLcm(Long.MIN_VALUE, 0));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
#include "gcd.h"
#include <stdlib.h>
void gcd_and_lcm(long long a, long long b, long long *gcd, long long *lcm) {
// The remainder in C has the sign of the dividend, so the loop works on
// the absolute values.
long long x = llabs(a);
long long y = llabs(b);
while (y != 0) {
long long r = x % y;
x = y;
y = r;
}
*gcd = x;
*lcm = a == 0 || b == 0 ? 0 : llabs(a) / x * llabs(b);
}
gcd.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
#ifndef GCD_AND_LCM_H
#define GCD_AND_LCM_H
// Sets *gcd and *lcm for a and b. Neither a nor b can be LLONG_MIN, and the
// least common multiple must fit in a long long.
void gcd_and_lcm(long long a, long long b, long long *gcd, long long *lcm);
#endif
test_gcd.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
#include "gcd.h"
#include <stdio.h>
#include <stdlib.h>
struct test_case {
const char *name;
long long a, b, gcd, lcm;
};
static const struct test_case cases[] = {
{"common-factor", 12, 18, 6, 36},
{"coprime", 17, 5, 1, 85},
{"euclid-example", 48, 180, 12, 720},
{"zero-and-number", 0, 7, 7, 0},
{"both-zero", 0, 0, 0, 0},
{"negative", -12, 18, 6, 36},
{"both-negative", -4, -6, 2, 12},
{"equal", 9, 9, 9, 9},
{"one", 1, 1000000007, 1, 1000000007},
{"multiple", 5, 25, 5, 25},
{"fibonacci", 832040, 514229, 1, 427859097160LL},
{"big-lcm", 3000000000000000000LL, 6000000000000000000LL, 3000000000000000000LL, 6000000000000000000LL},
{"largest", 9223372036854775807LL, -9223372036854775807LL, 9223372036854775807LL, 9223372036854775807LL},
};
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
long long g1, l1, g2, l2;
gcd_and_lcm(c->a, c->b, &g1, &l1);
gcd_and_lcm(c->b, c->a, &g2, &l2);
if (g1 != c->gcd || l1 != c->lcm || g2 != c->gcd || l2 != c->lcm) {
printf("FAIL %s: (%lld, %lld)\n", c->name, g1, l1);
failures++;
}
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
using System;
/// <summary>The greatest common divisor and the least common multiple of two long values.</summary>
public static class Gcd
{
/// <summary>Returns the GCD and the LCM. Math.Abs throws OverflowException for long.MinValue.</summary>
public static (long Gcd, long Lcm) GcdAndLcm(long a, long b)
{
long x = Math.Abs(a);
long y = Math.Abs(b);
while (y != 0)
{
(x, y) = (y, x % y);
}
long lcm = a == 0 || b == 0 ? 0 : checked(Math.Abs(a) / x * Math.Abs(b));
return (x, lcm);
}
}
GcdTests.cs 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
using System;
using System.Numerics;
using Xunit;
public sealed class GcdTests
{
public static TheoryData<string, long, long, long, long> Cases => new()
{
{ "common-factor", 12, 18, 6, 36 },
{ "coprime", 17, 5, 1, 85 },
{ "euclid-example", 48, 180, 12, 720 },
{ "zero-and-number", 0, 7, 7, 0 },
{ "both-zero", 0, 0, 0, 0 },
{ "negative", -12, 18, 6, 36 },
{ "both-negative", -4, -6, 2, 12 },
{ "equal", 9, 9, 9, 9 },
{ "one", 1, 1000000007, 1, 1000000007 },
{ "multiple", 5, 25, 5, 25 },
{ "fibonacci", 832040, 514229, 1, 427859097160 },
{ "big-lcm", 3000000000000000000, 6000000000000000000, 3000000000000000000, 6000000000000000000 },
{ "largest", 9223372036854775807, -9223372036854775807, 9223372036854775807, 9223372036854775807 },
};
[Theory]
[MemberData(nameof(Cases))]
public void GcdAndLcm(string name, long a, long b, long gcd, long lcm)
{
Assert.NotNull(name);
Assert.Equal((gcd, lcm), Gcd.GcdAndLcm(a, b));
Assert.Equal((gcd, lcm), Gcd.GcdAndLcm(b, a));
Assert.Equal(new BigInteger(gcd), BigInteger.GreatestCommonDivisor(a, b));
}
[Fact]
public void SmallestValueThrows()
{
Assert.Throws<OverflowException>(() => Gcd.GcdAndLcm(long.MinValue, 0));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
const abs = (x) => (x < 0n ? -x : x);
/** Returns [gcd, lcm] of two BigInt values with Euclid's algorithm. */
export function gcdAndLcm(a, b) {
let x = abs(a);
let y = abs(b);
while (y !== 0n) {
[x, y] = [y, x % y];
}
const lcm = a === 0n || b === 0n ? 0n : (abs(a) / x) * abs(b);
return [x, lcm];
}
gcd.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { gcdAndLcm } from "./gcd.js";
const cases = [
["common-factor", 12n, 18n, [6n, 36n]],
["coprime", 17n, 5n, [1n, 85n]],
["euclid-example", 48n, 180n, [12n, 720n]],
["zero-and-number", 0n, 7n, [7n, 0n]],
["both-zero", 0n, 0n, [0n, 0n]],
["negative", -12n, 18n, [6n, 36n]],
["both-negative", -4n, -6n, [2n, 12n]],
["equal", 9n, 9n, [9n, 9n]],
["one", 1n, 1000000007n, [1n, 1000000007n]],
["multiple", 5n, 25n, [5n, 25n]],
["fibonacci", 832040n, 514229n, [1n, 427859097160n]],
["big-lcm", 3000000000000000000n, 6000000000000000000n, [3000000000000000000n, 6000000000000000000n]],
["largest", 9223372036854775807n, -9223372036854775807n, [9223372036854775807n, 9223372036854775807n]],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.deepEqual(gcdAndLcm(a, b), want);
assert.deepEqual(gcdAndLcm(b, a), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
const abs = (x: bigint): bigint => (x < 0n ? -x : x);
/** Returns [gcd, lcm] of two bigint values with Euclid's algorithm. */
export function gcdAndLcm(a: bigint, b: bigint): [bigint, bigint] {
let x = abs(a);
let y = abs(b);
while (y !== 0n) {
[x, y] = [y, x % y];
}
const lcm = a === 0n || b === 0n ? 0n : (abs(a) / x) * abs(b);
return [x, lcm];
}
gcd.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { gcdAndLcm } from "./gcd.ts";
const cases: [string, bigint, bigint, [bigint, bigint]][] = [
["common-factor", 12n, 18n, [6n, 36n]],
["coprime", 17n, 5n, [1n, 85n]],
["euclid-example", 48n, 180n, [12n, 720n]],
["zero-and-number", 0n, 7n, [7n, 0n]],
["both-zero", 0n, 0n, [0n, 0n]],
["negative", -12n, 18n, [6n, 36n]],
["both-negative", -4n, -6n, [2n, 12n]],
["equal", 9n, 9n, [9n, 9n]],
["one", 1n, 1000000007n, [1n, 1000000007n]],
["multiple", 5n, 25n, [5n, 25n]],
["fibonacci", 832040n, 514229n, [1n, 427859097160n]],
["big-lcm", 3000000000000000000n, 6000000000000000000n, [3000000000000000000n, 6000000000000000000n]],
["largest", 9223372036854775807n, -9223372036854775807n, [9223372036854775807n, 9223372036854775807n]],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.deepEqual(gcdAndLcm(a, b), want);
assert.deepEqual(gcdAndLcm(b, a), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
// Package gcd computes the greatest common divisor and the least common
// multiple of two integers.
package gcd
func abs(x int64) int64 {
if x < 0 {
return -x
}
return x
}
// GcdAndLcm returns the greatest common divisor and the least common
// multiple of a and b with Euclid's algorithm. The remainder in Go has the
// sign of the dividend, so the loop works on the absolute values.
func GcdAndLcm(a, b int64) (gcd, lcm int64) {
x, y := abs(a), abs(b)
for y != 0 {
x, y = y, x%y
}
if a == 0 || b == 0 {
return x, 0
}
return x, abs(a) / x * abs(b)
}
gcd_test.go 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
package gcd
import (
"math/big"
"testing"
)
var cases = []struct {
name string
a, b int64
gcd, lcm int64
}{
{"common-factor", 12, 18, 6, 36},
{"coprime", 17, 5, 1, 85},
{"euclid-example", 48, 180, 12, 720},
{"zero-and-number", 0, 7, 7, 0},
{"both-zero", 0, 0, 0, 0},
{"negative", -12, 18, 6, 36},
{"both-negative", -4, -6, 2, 12},
{"equal", 9, 9, 9, 9},
{"one", 1, 1000000007, 1, 1000000007},
{"multiple", 5, 25, 5, 25},
{"fibonacci", 832040, 514229, 1, 427859097160},
{"big-lcm", 3000000000000000000, 6000000000000000000, 3000000000000000000, 6000000000000000000},
{"largest", 9223372036854775807, -9223372036854775807, 9223372036854775807, 9223372036854775807},
}
func TestGcdAndLcm(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
for _, p := range [][2]int64{{c.a, c.b}, {c.b, c.a}} {
gcd, lcm := GcdAndLcm(p[0], p[1])
if gcd != c.gcd || lcm != c.lcm {
t.Fatalf("GcdAndLcm(%d, %d) = (%d, %d), want (%d, %d)", p[0], p[1], gcd, lcm, c.gcd, c.lcm)
}
}
var z big.Int
z.GCD(nil, nil, big.NewInt(c.a), big.NewInt(c.b))
if !z.IsInt64() || z.Int64() != c.gcd {
t.Fatalf("big.Int GCD = %v", &z)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
/// Returns the greatest common divisor and the least common multiple of a
/// and b. unsigned_abs gives a u64, so the loop has no signs.
///
/// # Panics
///
/// Panics if a result does not fit in an i64.
pub fn gcd_and_lcm(a: i64, b: i64) -> (i64, i64) {
let (mut x, mut y) = (a.unsigned_abs(), b.unsigned_abs());
while y != 0 {
(x, y) = (y, x % y);
}
let lcm = if a == 0 || b == 0 {
0
} else {
(a.unsigned_abs() / x)
.checked_mul(b.unsigned_abs())
.expect("the lcm does not fit")
};
(
i64::try_from(x).expect("the gcd does not fit"),
i64::try_from(lcm).expect("the lcm does not fit"),
)
}
tests/gcd_test.rs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
use algo_compute_the_greatest_common_divisor::gcd_and_lcm;
const CASES: &[(&str, i64, i64, (i64, i64))] = &[
("common-factor", 12, 18, (6, 36)),
("coprime", 17, 5, (1, 85)),
("euclid-example", 48, 180, (12, 720)),
("zero-and-number", 0, 7, (7, 0)),
("both-zero", 0, 0, (0, 0)),
("negative", -12, 18, (6, 36)),
("both-negative", -4, -6, (2, 12)),
("equal", 9, 9, (9, 9)),
("one", 1, 1000000007, (1, 1000000007)),
("multiple", 5, 25, (5, 25)),
("fibonacci", 832040, 514229, (1, 427859097160)),
("big-lcm", 3000000000000000000, 6000000000000000000, (3000000000000000000, 6000000000000000000)),
("largest", 9223372036854775807, -9223372036854775807, (9223372036854775807, 9223372036854775807)),
];
#[test]
fn cases() {
for &(name, a, b, want) in CASES {
assert_eq!(gcd_and_lcm(a, b), want, "{name}");
assert_eq!(gcd_and_lcm(b, a), want, "{name}");
}
}
#[test]
#[should_panic(expected = "the gcd does not fit")]
fn smallest_value_panics() {
gcd_and_lcm(i64::MIN, 0);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
# gcd_and_lcm A B
# Prints "gcd lcm". The remainder in Bash has the sign of the dividend, so
# the loop works on the absolute values.
gcd_and_lcm() {
local a=$1 b=$2 x y r
x=$((a < 0 ? -a : a))
y=$((b < 0 ? -b : b))
while ((y != 0)); do
r=$((x % y))
x=$y
y=$r
done
if ((a == 0 || b == 0)); then
printf '%s 0\n' "$x"
else
printf '%s %s\n' "$x" "$(((a < 0 ? -a : a) / x * (b < 0 ? -b : b)))"
fi
}
test_gcd.bats 21 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-greatest-common-divisor/.
setup() {
source "$BATS_TEST_DIRNAME/gcd.sh"
}
@test "common-factor" { run gcd_and_lcm 12 18; [ "$output" = "6 36" ]; run gcd_and_lcm 18 12; [ "$output" = "6 36" ]; }
@test "coprime" { run gcd_and_lcm 17 5; [ "$output" = "1 85" ]; run gcd_and_lcm 5 17; [ "$output" = "1 85" ]; }
@test "euclid-example" { run gcd_and_lcm 48 180; [ "$output" = "12 720" ]; run gcd_and_lcm 180 48; [ "$output" = "12 720" ]; }
@test "zero-and-number" { run gcd_and_lcm 0 7; [ "$output" = "7 0" ]; run gcd_and_lcm 7 0; [ "$output" = "7 0" ]; }
@test "both-zero" { run gcd_and_lcm 0 0; [ "$output" = "0 0" ]; run gcd_and_lcm 0 0; [ "$output" = "0 0" ]; }
@test "negative" { run gcd_and_lcm -12 18; [ "$output" = "6 36" ]; run gcd_and_lcm 18 -12; [ "$output" = "6 36" ]; }
@test "both-negative" { run gcd_and_lcm -4 -6; [ "$output" = "2 12" ]; run gcd_and_lcm -6 -4; [ "$output" = "2 12" ]; }
@test "equal" { run gcd_and_lcm 9 9; [ "$output" = "9 9" ]; run gcd_and_lcm 9 9; [ "$output" = "9 9" ]; }
@test "one" { run gcd_and_lcm 1 1000000007; [ "$output" = "1 1000000007" ]; run gcd_and_lcm 1000000007 1; [ "$output" = "1 1000000007" ]; }
@test "multiple" { run gcd_and_lcm 5 25; [ "$output" = "5 25" ]; run gcd_and_lcm 25 5; [ "$output" = "5 25" ]; }
@test "fibonacci" { run gcd_and_lcm 832040 514229; [ "$output" = "1 427859097160" ]; run gcd_and_lcm 514229 832040; [ "$output" = "1 427859097160" ]; }
@test "big-lcm" { run gcd_and_lcm 3000000000000000000 6000000000000000000; [ "$output" = "3000000000000000000 6000000000000000000" ]; run gcd_and_lcm 6000000000000000000 3000000000000000000; [ "$output" = "3000000000000000000 6000000000000000000" ]; }
@test "largest" { run gcd_and_lcm 9223372036854775807 -9223372036854775807; [ "$output" = "9223372036854775807 9223372036854775807" ]; run gcd_and_lcm -9223372036854775807 9223372036854775807; [ "$output" = "9223372036854775807 9223372036854775807" ]; }
References
- Wikipedia, Euclidean algorithm, the introduction; Number of steps
- Rosetta Code, Greatest common divisor (task text, from acmeism/RosettaCodeData), task text
- Rosetta Code, Least common multiple (task text, from acmeism/RosettaCodeData), task text
- The Python Standard Library, math.integer, gcd; lcm
- Java SE 25 API, Class BigInteger, gcd(BigInteger)
- Java SE 25 API, Class Math, abs(long); absExact(long)
- .NET API reference, BigInteger.GreatestCommonDivisor method, Remarks
- Go standard library, math/big, func (*Int) GCD
- cppreference.com, std::gcd, Return value
- cppreference.com, std::lcm, Return value
- The Go Programming Language Specification, Integer operators
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 7JSP23 Edit this page History Report an error Markdown