diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ab7b15..a93b17a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to this project will be documented in this file. +## [0.10.1](https://github.com/brick/math/releases/tag/0.10.1) - 2022-08-02 + +✨ **New features** + +- `BigInteger::gcdMultiple()` returns the GCD of multiple `BigInteger` numbers + ## [0.10.0](https://github.com/brick/math/releases/tag/0.10.0) - 2022-06-18 💥 **Breaking changes** diff --git a/src/BigInteger.php b/src/BigInteger.php index f5da88d..f58e1c5 100644 --- a/src/BigInteger.php +++ b/src/BigInteger.php @@ -359,6 +359,21 @@ public static function ten() : BigInteger return $ten; } + public static function gcdMultiple(BigInteger $a, BigInteger ...$n): BigInteger + { + $result = $a; + + foreach ($n as $next) { + $result = $result->gcd($next); + + if ($result->isEqualTo(1)) { + return $result; + } + } + + return $result; + } + /** * Returns the sum of this number and the given one. * diff --git a/tests/BigIntegerTest.php b/tests/BigIntegerTest.php index 5daa035..2c4aa89 100644 --- a/tests/BigIntegerTest.php +++ b/tests/BigIntegerTest.php @@ -374,6 +374,46 @@ public function testTen() : void self::assertSame(BigInteger::ten(), BigInteger::ten()); } + /** + * @param string[] $values + * + * @dataProvider providerGcdMultiple + */ + public function testGcdMultiple(array $values, string $expectedGCD): void + { + $values = array_map(fn (string $value) => BigInteger::of($value), $values); + $actualGCD = BigInteger::gcdMultiple(...$values); + + self::assertSame($expectedGCD, (string) $actualGCD); + } + + public function providerGcdMultiple(): Generator + { + // 1 value + foreach (['-2', '-1', '0', '1', '2'] as $value) { + yield [[$value], $value]; + } + + // 2 values + foreach ($this->providerGcd() as [$a, $b, $gcd]) { + yield [[$a, $b], $gcd]; + } + + // n values + yield [['2', '4', '7'], '1']; + yield [['2', '4', '8'], '2']; + yield [['2', '4', '-7'], '1']; + yield [['2', '4', '-8'], '2']; + yield [['28', '56', '77777'], '7']; + yield [['28', '56', '77778'], '2']; + yield [['28', '56', '77782'], '2']; + yield [['28', '56', '77783'], '1']; + yield [['28', '56', '77784'], '28']; + yield [['28', '56', '77784', '4'], '4']; + yield [['28', '56', '77784', '14'], '14']; + yield [['28', '56', '77784', '14', '4'], '2']; + } + /** * @dataProvider providerMin *