Skip to content

Commit

Permalink
Add BigInteger::gcdMultiple()
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorel committed Aug 1, 2022
1 parent 9b153ea commit de84657
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Expand Up @@ -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**
Expand Down
15 changes: 15 additions & 0 deletions src/BigInteger.php
Expand Up @@ -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.
*
Expand Down
40 changes: 40 additions & 0 deletions tests/BigIntegerTest.php
Expand Up @@ -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
*
Expand Down

0 comments on commit de84657

Please sign in to comment.