Skip to content

Commit 957ea63

Browse files
committed
Fix BigInteger::gcdAll() returning negative value when using a single operand
1 parent e4481bd commit 957ea63

File tree

3 files changed

+13
-6
lines changed

3 files changed

+13
-6
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ All notable changes to this project will be documented in this file.
1010
- New method: `BigInteger::lcmAll()`
1111
- New method: `BigRational::toRepeatingDecimalString()`
1212

13+
🐛 **Bug fixes**
14+
15+
- `BigInteger::gcdAll()` / `gcdMultiple()` could return a negative result when used with a single negative number
16+
1317
## [0.14.2](https://github.com/brick/math/releases/tag/0.14.2) - 2026-01-30
1418

1519
🗑️ **Deprecations**

src/BigInteger.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,7 +354,7 @@ public static function ten(): BigInteger
354354
*/
355355
public static function gcdAll(BigNumber|int|float|string $a, BigNumber|int|float|string ...$n): BigInteger
356356
{
357-
$result = BigInteger::of($a);
357+
$result = BigInteger::of($a)->abs();
358358

359359
foreach ($n as $next) {
360360
$result = $result->gcd(BigInteger::of($next));

tests/BigIntegerTest.php

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -393,17 +393,17 @@ public function testTen(): void
393393
}
394394

395395
#[DataProvider('providerGcdAll')]
396-
public function testGcdAll(array $values, string $expectedGCD): void
396+
public function testGcdAll(array $values, string|int $expectedGCD): void
397397
{
398-
self::assertSame($expectedGCD, (string) BigInteger::gcdAll(...$values));
399-
self::assertSame($expectedGCD, (string) BigInteger::gcdMultiple(...$values));
398+
self::assertBigIntegerEquals((string) $expectedGCD, BigInteger::gcdAll(...$values));
399+
self::assertBigIntegerEquals((string) $expectedGCD, BigInteger::gcdMultiple(...$values));
400400
}
401401

402402
public static function providerGcdAll(): Generator
403403
{
404404
// 1 value
405-
foreach (['-2', '-1', '0', '1', '2'] as $value) {
406-
yield [[$value], $value];
405+
foreach ([-4, -3, -2, -1, 0, 1, 2, 3, 4] as $value) {
406+
yield [[$value], abs($value)];
407407
}
408408

409409
// 2 values
@@ -417,6 +417,9 @@ public static function providerGcdAll(): Generator
417417
yield [['2', '4', '-7'], '1'];
418418
yield [['2', '4', '-8'], '2'];
419419
yield [['28', '56', '77777'], '7'];
420+
yield [['-28', '56', '77777'], '7'];
421+
yield [['-28', '-56', '77777'], '7'];
422+
yield [['-28', '-56', '-77777'], '7'];
420423
yield [['28', '56', '77778'], '2'];
421424
yield [['28', '56', '77782'], '2'];
422425
yield [['28', '56', '77783'], '1'];

0 commit comments

Comments
 (0)