Skip to content

Commit de84657

Browse files
committed
Add BigInteger::gcdMultiple()
1 parent 9b153ea commit de84657

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22

33
All notable changes to this project will be documented in this file.
44

5+
## [0.10.1](https://github.com/brick/math/releases/tag/0.10.1) - 2022-08-02
6+
7+
**New features**
8+
9+
- `BigInteger::gcdMultiple()` returns the GCD of multiple `BigInteger` numbers
10+
511
## [0.10.0](https://github.com/brick/math/releases/tag/0.10.0) - 2022-06-18
612

713
💥 **Breaking changes**

src/BigInteger.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,21 @@ public static function ten() : BigInteger
359359
return $ten;
360360
}
361361

362+
public static function gcdMultiple(BigInteger $a, BigInteger ...$n): BigInteger
363+
{
364+
$result = $a;
365+
366+
foreach ($n as $next) {
367+
$result = $result->gcd($next);
368+
369+
if ($result->isEqualTo(1)) {
370+
return $result;
371+
}
372+
}
373+
374+
return $result;
375+
}
376+
362377
/**
363378
* Returns the sum of this number and the given one.
364379
*

tests/BigIntegerTest.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,46 @@ public function testTen() : void
374374
self::assertSame(BigInteger::ten(), BigInteger::ten());
375375
}
376376

377+
/**
378+
* @param string[] $values
379+
*
380+
* @dataProvider providerGcdMultiple
381+
*/
382+
public function testGcdMultiple(array $values, string $expectedGCD): void
383+
{
384+
$values = array_map(fn (string $value) => BigInteger::of($value), $values);
385+
$actualGCD = BigInteger::gcdMultiple(...$values);
386+
387+
self::assertSame($expectedGCD, (string) $actualGCD);
388+
}
389+
390+
public function providerGcdMultiple(): Generator
391+
{
392+
// 1 value
393+
foreach (['-2', '-1', '0', '1', '2'] as $value) {
394+
yield [[$value], $value];
395+
}
396+
397+
// 2 values
398+
foreach ($this->providerGcd() as [$a, $b, $gcd]) {
399+
yield [[$a, $b], $gcd];
400+
}
401+
402+
// n values
403+
yield [['2', '4', '7'], '1'];
404+
yield [['2', '4', '8'], '2'];
405+
yield [['2', '4', '-7'], '1'];
406+
yield [['2', '4', '-8'], '2'];
407+
yield [['28', '56', '77777'], '7'];
408+
yield [['28', '56', '77778'], '2'];
409+
yield [['28', '56', '77782'], '2'];
410+
yield [['28', '56', '77783'], '1'];
411+
yield [['28', '56', '77784'], '28'];
412+
yield [['28', '56', '77784', '4'], '4'];
413+
yield [['28', '56', '77784', '14'], '14'];
414+
yield [['28', '56', '77784', '14', '4'], '2'];
415+
}
416+
377417
/**
378418
* @dataProvider providerMin
379419
*

0 commit comments

Comments
 (0)