• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

brick / math / 17335584781

29 Aug 2025 10:33PM UTC coverage: 99.743%. Remained the same
17335584781

push

github

BenMorel
Apply ECS

209 of 264 new or added lines in 10 files covered. (79.17%)

139 existing lines in 4 files now uncovered.

1165 of 1168 relevant lines covered (99.74%)

1135.14 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.28
/src/BigInteger.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Brick\Math;
6

7
use Brick\Math\Exception\DivisionByZeroException;
8
use Brick\Math\Exception\IntegerOverflowException;
9
use Brick\Math\Exception\MathException;
10
use Brick\Math\Exception\NegativeNumberException;
11
use Brick\Math\Exception\NumberFormatException;
12
use Brick\Math\Internal\Calculator;
13
use Brick\Math\Internal\CalculatorRegistry;
14
use InvalidArgumentException;
15
use LogicException;
16
use Override;
17

18
use function assert;
19
use function bin2hex;
20
use function chr;
21
use function hex2bin;
22
use function in_array;
23
use function intdiv;
24
use function ltrim;
25
use function ord;
26
use function preg_match;
27
use function preg_quote;
28
use function random_bytes;
29
use function sprintf;
30
use function str_repeat;
31
use function strlen;
32
use function strtolower;
33
use function substr;
34

35
/**
36
 * An arbitrary-size integer.
37
 *
38
 * All methods accepting a number as a parameter accept either a BigInteger instance,
39
 * an integer, or a string representing an arbitrary size integer.
40
 */
41
final readonly class BigInteger extends BigNumber
42
{
43
    /**
44
     * The value, as a string of digits with optional leading minus sign.
45
     *
46
     * No leading zeros must be present.
47
     * No leading minus sign must be present if the number is zero.
48
     */
49
    private string $value;
50

51
    /**
52
     * Protected constructor. Use a factory method to obtain an instance.
53
     *
54
     * @param string $value A string of digits, with optional leading minus sign.
55
     *
56
     * @pure
57
     */
58
    protected function __construct(string $value)
59
    {
60
        $this->value = $value;
18,863✔
61
    }
62

63
    /**
64
     * Creates a number from a string in a given base.
65
     *
66
     * The string can optionally be prefixed with the `+` or `-` sign.
67
     *
68
     * Bases greater than 36 are not supported by this method, as there is no clear consensus on which of the lowercase
69
     * or uppercase characters should come first. Instead, this method accepts any base up to 36, and does not
70
     * differentiate lowercase and uppercase characters, which are considered equal.
71
     *
72
     * For bases greater than 36, and/or custom alphabets, use the fromArbitraryBase() method.
73
     *
74
     * @param string $number The number to convert, in the given base.
75
     * @param int    $base   The base of the number, between 2 and 36.
76
     *
77
     * @throws NumberFormatException    If the number is empty, or contains invalid chars for the given base.
78
     * @throws InvalidArgumentException If the base is out of range.
79
     *
80
     * @pure
81
     */
82
    public static function fromBase(string $number, int $base): BigInteger
83
    {
84
        if ($number === '') {
2,093✔
85
            throw new NumberFormatException('The number cannot be empty.');
3✔
86
        }
87

88
        if ($base < 2 || $base > 36) {
2,090✔
89
            throw new InvalidArgumentException(sprintf('Base %d is not in range 2 to 36.', $base));
15✔
90
        }
91

92
        if ($number[0] === '-') {
2,075✔
93
            $sign = '-';
27✔
94
            $number = substr($number, 1);
27✔
95
        } elseif ($number[0] === '+') {
2,048✔
96
            $sign = '';
27✔
97
            $number = substr($number, 1);
27✔
98
        } else {
99
            $sign = '';
2,021✔
100
        }
101

102
        if ($number === '') {
2,075✔
103
            throw new NumberFormatException('The number cannot be empty.');
6✔
104
        }
105

106
        $number = ltrim($number, '0');
2,069✔
107

108
        if ($number === '') {
2,069✔
109
            // The result will be the same in any base, avoid further calculation.
110
            return BigInteger::zero();
84✔
111
        }
112

113
        if ($number === '1') {
1,988✔
114
            // The result will be the same in any base, avoid further calculation.
115
            return new BigInteger($sign . '1');
75✔
116
        }
117

118
        $pattern = '/[^' . substr(Calculator::ALPHABET, 0, $base) . ']/';
1,916✔
119

120
        if (preg_match($pattern, strtolower($number), $matches) === 1) {
1,916✔
121
            throw new NumberFormatException(sprintf('"%s" is not a valid character in base %d.', $matches[0], $base));
111✔
122
        }
123

124
        if ($base === 10) {
1,805✔
125
            // The number is usable as is, avoid further calculation.
126
            return new BigInteger($sign . $number);
24✔
127
        }
128

129
        $result = CalculatorRegistry::get()->fromBase($number, $base);
1,781✔
130

131
        return new BigInteger($sign . $result);
1,781✔
132
    }
133

134
    /**
135
     * Parses a string containing an integer in an arbitrary base, using a custom alphabet.
136
     *
137
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers.
138
     *
139
     * @param string $number   The number to parse.
140
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
141
     *
142
     * @throws NumberFormatException    If the given number is empty or contains invalid chars for the given alphabet.
143
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars.
144
     *
145
     * @pure
146
     */
147
    public static function fromArbitraryBase(string $number, string $alphabet): BigInteger
148
    {
149
        if ($number === '') {
411✔
150
            throw new NumberFormatException('The number cannot be empty.');
3✔
151
        }
152

153
        $base = strlen($alphabet);
408✔
154

155
        if ($base < 2) {
408✔
156
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
157
        }
158

159
        $pattern = '/[^' . preg_quote($alphabet, '/') . ']/';
402✔
160

161
        if (preg_match($pattern, $number, $matches) === 1) {
402✔
162
            throw NumberFormatException::charNotInAlphabet($matches[0]);
24✔
163
        }
164

165
        $number = CalculatorRegistry::get()->fromArbitraryBase($number, $alphabet, $base);
378✔
166

167
        return new BigInteger($number);
378✔
168
    }
169

170
    /**
171
     * Translates a string of bytes containing the binary representation of a BigInteger into a BigInteger.
172
     *
173
     * The input string is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.
174
     *
175
     * If `$signed` is true, the input is assumed to be in two's-complement representation, and the leading bit is
176
     * interpreted as a sign bit. If `$signed` is false, the input is interpreted as an unsigned number, and the
177
     * resulting BigInteger will always be positive or zero.
178
     *
179
     * This method can be used to retrieve a number exported by `toBytes()`, as long as the `$signed` flags match.
180
     *
181
     * @param string $value  The byte string.
182
     * @param bool   $signed Whether to interpret as a signed number in two's-complement representation with a leading
183
     *                       sign bit.
184
     *
185
     * @throws NumberFormatException If the string is empty.
186
     *
187
     * @pure
188
     */
189
    public static function fromBytes(string $value, bool $signed = true): BigInteger
190
    {
191
        if ($value === '') {
1,224✔
192
            throw new NumberFormatException('The byte string must not be empty.');
3✔
193
        }
194

195
        $twosComplement = false;
1,221✔
196

197
        if ($signed) {
1,221✔
198
            $x = ord($value[0]);
984✔
199

200
            if (($twosComplement = ($x >= 0x80))) {
984✔
201
                $value = ~$value;
906✔
202
            }
203
        }
204

205
        $number = self::fromBase(bin2hex($value), 16);
1,221✔
206

207
        if ($twosComplement) {
1,221✔
208
            return $number->plus(1)->negated();
906✔
209
        }
210

211
        return $number;
315✔
212
    }
213

214
    /**
215
     * Generates a pseudo-random number in the range 0 to 2^numBits - 1.
216
     *
217
     * Using the default random bytes generator, this method is suitable for cryptographic use.
218
     *
219
     * @param int                          $numBits              The number of bits.
220
     * @param (callable(int): string)|null $randomBytesGenerator A function that accepts a number of bytes, and returns
221
     *                                                           a string of random bytes of the given length. Defaults
222
     *                                                           to the `random_bytes()` function.
223
     *
224
     * @throws InvalidArgumentException If $numBits is negative.
225
     */
226
    public static function randomBits(int $numBits, ?callable $randomBytesGenerator = null): BigInteger
227
    {
228
        if ($numBits < 0) {
165✔
229
            throw new InvalidArgumentException('The number of bits cannot be negative.');
3✔
230
        }
231

232
        if ($numBits === 0) {
162✔
233
            return BigInteger::zero();
3✔
234
        }
235

236
        if ($randomBytesGenerator === null) {
159✔
UNCOV
237
            $randomBytesGenerator = random_bytes(...);
×
238
        }
239

240
        /** @var int<1, max> $byteLength */
241
        $byteLength = intdiv($numBits - 1, 8) + 1;
159✔
242

243
        $extraBits = ($byteLength * 8 - $numBits);
159✔
244
        $bitmask = chr(0xFF >> $extraBits);
159✔
245

246
        $randomBytes = $randomBytesGenerator($byteLength);
159✔
247
        $randomBytes[0] = $randomBytes[0] & $bitmask;
159✔
248

249
        return self::fromBytes($randomBytes, false);
159✔
250
    }
251

252
    /**
253
     * Generates a pseudo-random number between `$min` and `$max`.
254
     *
255
     * Using the default random bytes generator, this method is suitable for cryptographic use.
256
     *
257
     * @param BigNumber|int|float|string   $min                  The lower bound. Must be convertible to a BigInteger.
258
     * @param BigNumber|int|float|string   $max                  The upper bound. Must be convertible to a BigInteger.
259
     * @param (callable(int): string)|null $randomBytesGenerator A function that accepts a number of bytes, and returns
260
     *                                                           a string of random bytes of the given length. Defaults
261
     *                                                           to the `random_bytes()` function.
262
     *
263
     * @throws MathException If one of the parameters cannot be converted to a BigInteger,
264
     *                       or `$min` is greater than `$max`.
265
     */
266
    public static function randomRange(
267
        BigNumber|int|float|string $min,
268
        BigNumber|int|float|string $max,
269
        ?callable $randomBytesGenerator = null,
270
    ): BigInteger {
271
        $min = BigInteger::of($min);
84✔
272
        $max = BigInteger::of($max);
84✔
273

274
        if ($min->isGreaterThan($max)) {
84✔
275
            throw new MathException('$min cannot be greater than $max.');
3✔
276
        }
277

278
        if ($min->isEqualTo($max)) {
81✔
279
            return $min;
3✔
280
        }
281

282
        $diff = $max->minus($min);
78✔
283
        $bitLength = $diff->getBitLength();
78✔
284

285
        // try until the number is in range (50% to 100% chance of success)
286
        do {
287
            $randomNumber = self::randomBits($bitLength, $randomBytesGenerator);
78✔
288
        } while ($randomNumber->isGreaterThan($diff));
78✔
289

290
        return $randomNumber->plus($min);
78✔
291
    }
292

293
    /**
294
     * Returns a BigInteger representing zero.
295
     *
296
     * @pure
297
     */
298
    public static function zero(): BigInteger
299
    {
300
        /** @var BigInteger|null $zero */
301
        static $zero;
111✔
302

303
        if ($zero === null) {
111✔
UNCOV
304
            $zero = new BigInteger('0');
×
305
        }
306

307
        return $zero;
111✔
308
    }
309

310
    /**
311
     * Returns a BigInteger representing one.
312
     *
313
     * @pure
314
     */
315
    public static function one(): BigInteger
316
    {
317
        /** @var BigInteger|null $one */
318
        static $one;
444✔
319

320
        if ($one === null) {
444✔
321
            $one = new BigInteger('1');
3✔
322
        }
323

324
        return $one;
444✔
325
    }
326

327
    /**
328
     * Returns a BigInteger representing ten.
329
     *
330
     * @pure
331
     */
332
    public static function ten(): BigInteger
333
    {
334
        /** @var BigInteger|null $ten */
335
        static $ten;
6✔
336

337
        if ($ten === null) {
6✔
338
            $ten = new BigInteger('10');
3✔
339
        }
340

341
        return $ten;
6✔
342
    }
343

344
    /**
345
     * @pure
346
     */
347
    public static function gcdMultiple(BigInteger $a, BigInteger ...$n): BigInteger
348
    {
349
        $result = $a;
1,563✔
350

351
        foreach ($n as $next) {
1,563✔
352
            $result = $result->gcd($next);
1,548✔
353

354
            if ($result->isEqualTo(1)) {
1,548✔
355
                return $result;
345✔
356
            }
357
        }
358

359
        return $result;
1,218✔
360
    }
361

362
    /**
363
     * Returns the sum of this number and the given one.
364
     *
365
     * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigInteger.
366
     *
367
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
368
     *
369
     * @pure
370
     */
371
    public function plus(BigNumber|int|float|string $that): BigInteger
372
    {
373
        $that = BigInteger::of($that);
1,569✔
374

375
        if ($that->value === '0') {
1,569✔
376
            return $this;
21✔
377
        }
378

379
        if ($this->value === '0') {
1,548✔
380
            return $that;
63✔
381
        }
382

383
        $value = CalculatorRegistry::get()->add($this->value, $that->value);
1,506✔
384

385
        return new BigInteger($value);
1,506✔
386
    }
387

388
    /**
389
     * Returns the difference of this number and the given one.
390
     *
391
     * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigInteger.
392
     *
393
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
394
     *
395
     * @pure
396
     */
397
    public function minus(BigNumber|int|float|string $that): BigInteger
398
    {
399
        $that = BigInteger::of($that);
888✔
400

401
        if ($that->value === '0') {
888✔
402
            return $this;
24✔
403
        }
404

405
        $value = CalculatorRegistry::get()->sub($this->value, $that->value);
870✔
406

407
        return new BigInteger($value);
870✔
408
    }
409

410
    /**
411
     * Returns the product of this number and the given one.
412
     *
413
     * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigInteger.
414
     *
415
     * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger.
416
     *
417
     * @pure
418
     */
419
    public function multipliedBy(BigNumber|int|float|string $that): BigInteger
420
    {
421
        $that = BigInteger::of($that);
1,149✔
422

423
        if ($that->value === '1') {
1,149✔
424
            return $this;
270✔
425
        }
426

427
        if ($this->value === '1') {
1,137✔
428
            return $that;
294✔
429
        }
430

431
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
1,050✔
432

433
        return new BigInteger($value);
1,050✔
434
    }
435

436
    /**
437
     * Returns the result of the division of this number by the given one.
438
     *
439
     * @param BigNumber|int|float|string $that         The divisor. Must be convertible to a BigInteger.
440
     * @param RoundingMode               $roundingMode An optional rounding mode, defaults to UNNECESSARY.
441
     *
442
     * @throws MathException If the divisor is not a valid number, is not convertible to a BigInteger, is zero,
443
     *                       or RoundingMode::UNNECESSARY is used and the remainder is not zero.
444
     *
445
     * @pure
446
     */
447
    public function dividedBy(BigNumber|int|float|string $that, RoundingMode $roundingMode = RoundingMode::UNNECESSARY): BigInteger
448
    {
449
        $that = BigInteger::of($that);
1,980✔
450

451
        if ($that->value === '1') {
1,971✔
452
            return $this;
3✔
453
        }
454

455
        if ($that->value === '0') {
1,968✔
456
            throw DivisionByZeroException::divisionByZero();
6✔
457
        }
458

459
        $result = CalculatorRegistry::get()->divRound($this->value, $that->value, $roundingMode);
1,962✔
460

461
        return new BigInteger($result);
1,869✔
462
    }
463

464
    /**
465
     * Limits (clamps) this number between the given minimum and maximum values.
466
     *
467
     * If the number is lower than $min, returns a copy of $min.
468
     * If the number is greater than $max, returns a copy of $max.
469
     * Otherwise, returns this number unchanged.
470
     *
471
     * @param BigNumber|int|float|string $min The minimum. Must be convertible to a BigInteger.
472
     * @param BigNumber|int|float|string $max The maximum. Must be convertible to a BigInteger.
473
     *
474
     * @throws MathException If min/max are not convertible to a BigInteger.
475
     */
476
    public function clamp(BigNumber|int|float|string $min, BigNumber|int|float|string $max): BigInteger
477
    {
478
        if ($this->isLessThan($min)) {
30✔
479
            return BigInteger::of($min);
9✔
480
        } elseif ($this->isGreaterThan($max)) {
21✔
481
            return BigInteger::of($max);
3✔
482
        }
483

484
        return $this;
18✔
485
    }
486

487
    /**
488
     * Returns this number exponentiated to the given value.
489
     *
490
     * @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
491
     *
492
     * @pure
493
     */
494
    public function power(int $exponent): BigInteger
495
    {
496
        if ($exponent === 0) {
1,827✔
497
            return BigInteger::one();
21✔
498
        }
499

500
        if ($exponent === 1) {
1,806✔
501
            return $this;
198✔
502
        }
503

504
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
1,608✔
505
            throw new InvalidArgumentException(sprintf(
6✔
506
                'The exponent %d is not in the range 0 to %d.',
6✔
507
                $exponent,
6✔
508
                Calculator::MAX_POWER,
6✔
509
            ));
6✔
510
        }
511

512
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,602✔
513
    }
514

515
    /**
516
     * Returns the quotient of the division of this number by the given one.
517
     *
518
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
519
     *
520
     * @throws DivisionByZeroException If the divisor is zero.
521
     *
522
     * @pure
523
     */
524
    public function quotient(BigNumber|int|float|string $that): BigInteger
525
    {
526
        $that = BigInteger::of($that);
969✔
527

528
        if ($that->value === '1') {
969✔
529
            return $this;
66✔
530
        }
531

532
        if ($that->value === '0') {
903✔
533
            throw DivisionByZeroException::divisionByZero();
3✔
534
        }
535

536
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
900✔
537

538
        return new BigInteger($quotient);
900✔
539
    }
540

541
    /**
542
     * Returns the remainder of the division of this number by the given one.
543
     *
544
     * The remainder, when non-zero, has the same sign as the dividend.
545
     *
546
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
547
     *
548
     * @throws DivisionByZeroException If the divisor is zero.
549
     *
550
     * @pure
551
     */
552
    public function remainder(BigNumber|int|float|string $that): BigInteger
553
    {
554
        $that = BigInteger::of($that);
159✔
555

556
        if ($that->value === '1') {
159✔
557
            return BigInteger::zero();
12✔
558
        }
559

560
        if ($that->value === '0') {
147✔
561
            throw DivisionByZeroException::divisionByZero();
3✔
562
        }
563

564
        $remainder = CalculatorRegistry::get()->divR($this->value, $that->value);
144✔
565

566
        return new BigInteger($remainder);
144✔
567
    }
568

569
    /**
570
     * Returns the quotient and remainder of the division of this number by the given one.
571
     *
572
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
573
     *
574
     * @return array{BigInteger, BigInteger} An array containing the quotient and the remainder.
575
     *
576
     * @throws DivisionByZeroException If the divisor is zero.
577
     *
578
     * @pure
579
     */
580
    public function quotientAndRemainder(BigNumber|int|float|string $that): array
581
    {
582
        $that = BigInteger::of($that);
159✔
583

584
        if ($that->value === '0') {
159✔
585
            throw DivisionByZeroException::divisionByZero();
3✔
586
        }
587

588
        [$quotient, $remainder] = CalculatorRegistry::get()->divQR($this->value, $that->value);
156✔
589

590
        return [
156✔
591
            new BigInteger($quotient),
156✔
592
            new BigInteger($remainder),
156✔
593
        ];
156✔
594
    }
595

596
    /**
597
     * Returns the modulo of this number and the given one.
598
     *
599
     * The modulo operation yields the same result as the remainder operation when both operands are of the same sign,
600
     * and may differ when signs are different.
601
     *
602
     * The result of the modulo operation, when non-zero, has the same sign as the divisor.
603
     *
604
     * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigInteger.
605
     *
606
     * @throws DivisionByZeroException If the divisor is zero.
607
     *
608
     * @pure
609
     */
610
    public function mod(BigNumber|int|float|string $that): BigInteger
611
    {
612
        $that = BigInteger::of($that);
195✔
613

614
        if ($that->value === '0') {
195✔
615
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
616
        }
617

618
        $value = CalculatorRegistry::get()->mod($this->value, $that->value);
192✔
619

620
        return new BigInteger($value);
192✔
621
    }
622

623
    /**
624
     * Returns the modular multiplicative inverse of this BigInteger modulo $m.
625
     *
626
     * @throws DivisionByZeroException If $m is zero.
627
     * @throws NegativeNumberException If $m is negative.
628
     * @throws MathException           If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger
629
     *                                 is not relatively prime to m).
630
     *
631
     * @pure
632
     */
633
    public function modInverse(BigInteger $m): BigInteger
634
    {
635
        if ($m->value === '0') {
66✔
636
            throw DivisionByZeroException::modulusMustNotBeZero();
6✔
637
        }
638

639
        if ($m->isNegative()) {
60✔
640
            throw new NegativeNumberException('Modulus must not be negative.');
3✔
641
        }
642

643
        if ($m->value === '1') {
57✔
644
            return BigInteger::zero();
3✔
645
        }
646

647
        $value = CalculatorRegistry::get()->modInverse($this->value, $m->value);
54✔
648

649
        if ($value === null) {
54✔
650
            throw new MathException('Unable to compute the modInverse for the given modulus.');
15✔
651
        }
652

653
        return new BigInteger($value);
39✔
654
    }
655

656
    /**
657
     * Returns this number raised into power with modulo.
658
     *
659
     * This operation only works on positive numbers.
660
     *
661
     * @param BigNumber|int|float|string $exp The exponent. Must be positive or zero.
662
     * @param BigNumber|int|float|string $mod The modulus. Must be strictly positive.
663
     *
664
     * @throws NegativeNumberException If any of the operands is negative.
665
     * @throws DivisionByZeroException If the modulus is zero.
666
     *
667
     * @pure
668
     */
669
    public function modPow(BigNumber|int|float|string $exp, BigNumber|int|float|string $mod): BigInteger
670
    {
671
        $exp = BigInteger::of($exp);
47✔
672
        $mod = BigInteger::of($mod);
47✔
673

674
        if ($this->isNegative() || $exp->isNegative() || $mod->isNegative()) {
47✔
675
            throw new NegativeNumberException('The operands cannot be negative.');
9✔
676
        }
677

678
        if ($mod->isZero()) {
38✔
679
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
680
        }
681

682
        $result = CalculatorRegistry::get()->modPow($this->value, $exp->value, $mod->value);
35✔
683

684
        return new BigInteger($result);
35✔
685
    }
686

687
    /**
688
     * Returns the greatest common divisor of this number and the given one.
689
     *
690
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
691
     *
692
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
693
     *
694
     * @pure
695
     */
696
    public function gcd(BigNumber|int|float|string $that): BigInteger
697
    {
698
        $that = BigInteger::of($that);
3,198✔
699

700
        if ($that->value === '0' && $this->value[0] !== '-') {
3,198✔
701
            return $this;
60✔
702
        }
703

704
        if ($this->value === '0' && $that->value[0] !== '-') {
3,138✔
705
            return $that;
30✔
706
        }
707

708
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
3,108✔
709

710
        return new BigInteger($value);
3,108✔
711
    }
712

713
    /**
714
     * Returns the integer square root number of this number, rounded down.
715
     *
716
     * The result is the largest x such that x² ≤ n.
717
     *
718
     * @throws NegativeNumberException If this number is negative.
719
     *
720
     * @pure
721
     */
722
    public function sqrt(): BigInteger
723
    {
724
        if ($this->value[0] === '-') {
1,008✔
725
            throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
3✔
726
        }
727

728
        $value = CalculatorRegistry::get()->sqrt($this->value);
1,005✔
729

730
        return new BigInteger($value);
1,005✔
731
    }
732

733
    /**
734
     * Returns the absolute value of this number.
735
     *
736
     * @pure
737
     */
738
    public function abs(): BigInteger
739
    {
740
        return $this->isNegative() ? $this->negated() : $this;
678✔
741
    }
742

743
    /**
744
     * Returns the inverse of this number.
745
     *
746
     * @pure
747
     */
748
    public function negated(): BigInteger
749
    {
750
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
2,838✔
751
    }
752

753
    /**
754
     * Returns the integer bitwise-and combined with another integer.
755
     *
756
     * This method returns a negative BigInteger if and only if both operands are negative.
757
     *
758
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
759
     *
760
     * @pure
761
     */
762
    public function and(BigNumber|int|float|string $that): BigInteger
763
    {
764
        $that = BigInteger::of($that);
153✔
765

766
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
767
    }
768

769
    /**
770
     * Returns the integer bitwise-or combined with another integer.
771
     *
772
     * This method returns a negative BigInteger if and only if either of the operands is negative.
773
     *
774
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
775
     *
776
     * @pure
777
     */
778
    public function or(BigNumber|int|float|string $that): BigInteger
779
    {
780
        $that = BigInteger::of($that);
138✔
781

782
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
783
    }
784

785
    /**
786
     * Returns the integer bitwise-xor combined with another integer.
787
     *
788
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
789
     *
790
     * @param BigNumber|int|float|string $that The operand. Must be convertible to an integer number.
791
     *
792
     * @pure
793
     */
794
    public function xor(BigNumber|int|float|string $that): BigInteger
795
    {
796
        $that = BigInteger::of($that);
144✔
797

798
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
799
    }
800

801
    /**
802
     * Returns the bitwise-not of this BigInteger.
803
     *
804
     * @pure
805
     */
806
    public function not(): BigInteger
807
    {
808
        return $this->negated()->minus(1);
57✔
809
    }
810

811
    /**
812
     * Returns the integer left shifted by a given number of bits.
813
     *
814
     * @pure
815
     */
816
    public function shiftedLeft(int $distance): BigInteger
817
    {
818
        if ($distance === 0) {
594✔
819
            return $this;
6✔
820
        }
821

822
        if ($distance < 0) {
588✔
823
            return $this->shiftedRight(-$distance);
198✔
824
        }
825

826
        return $this->multipliedBy(BigInteger::of(2)->power($distance));
390✔
827
    }
828

829
    /**
830
     * Returns the integer right shifted by a given number of bits.
831
     *
832
     * @pure
833
     */
834
    public function shiftedRight(int $distance): BigInteger
835
    {
836
        if ($distance === 0) {
1,518✔
837
            return $this;
66✔
838
        }
839

840
        if ($distance < 0) {
1,452✔
841
            return $this->shiftedLeft(-$distance);
195✔
842
        }
843

844
        $operand = BigInteger::of(2)->power($distance);
1,257✔
845

846
        if ($this->isPositiveOrZero()) {
1,257✔
847
            return $this->quotient($operand);
672✔
848
        }
849

850
        return $this->dividedBy($operand, RoundingMode::UP);
585✔
851
    }
852

853
    /**
854
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
855
     *
856
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
857
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
858
     *
859
     * @pure
860
     */
861
    public function getBitLength(): int
862
    {
863
        if ($this->value === '0') {
321✔
864
            return 0;
12✔
865
        }
866

867
        if ($this->isNegative()) {
315✔
868
            return $this->abs()->minus(1)->getBitLength();
120✔
869
        }
870

871
        return strlen($this->toBase(2));
309✔
872
    }
873

874
    /**
875
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
876
     *
877
     * Returns -1 if this BigInteger contains no one bits.
878
     *
879
     * @pure
880
     */
881
    public function getLowestSetBit(): int
882
    {
883
        $n = $this;
81✔
884
        $bitLength = $this->getBitLength();
81✔
885

886
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
887
            if ($n->isOdd()) {
81✔
888
                return $i;
78✔
889
            }
890

891
            $n = $n->shiftedRight(1);
51✔
892
        }
893

894
        return -1;
3✔
895
    }
896

897
    /**
898
     * Returns whether this number is even.
899
     *
900
     * @pure
901
     */
902
    public function isEven(): bool
903
    {
904
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
905
    }
906

907
    /**
908
     * Returns whether this number is odd.
909
     *
910
     * @pure
911
     */
912
    public function isOdd(): bool
913
    {
914
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
915
    }
916

917
    /**
918
     * Returns true if and only if the designated bit is set.
919
     *
920
     * Computes ((this & (1<<n)) != 0).
921
     *
922
     * @param int $n The bit to test, 0-based.
923
     *
924
     * @throws InvalidArgumentException If the bit to test is negative.
925
     *
926
     * @pure
927
     */
928
    public function testBit(int $n): bool
929
    {
930
        if ($n < 0) {
873✔
931
            throw new InvalidArgumentException('The bit to test cannot be negative.');
3✔
932
        }
933

934
        return $this->shiftedRight($n)->isOdd();
870✔
935
    }
936

937
    #[Override]
938
    public function compareTo(BigNumber|int|float|string $that): int
939
    {
940
        $that = BigNumber::of($that);
2,312✔
941

942
        if ($that instanceof BigInteger) {
2,312✔
943
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,204✔
944
        }
945

946
        return -$that->compareTo($this);
108✔
947
    }
948

949
    #[Override]
950
    public function getSign(): int
951
    {
952
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
3,173✔
953
    }
954

955
    #[Override]
956
    public function toBigInteger(): BigInteger
957
    {
958
        return $this;
13,118✔
959
    }
960

961
    #[Override]
962
    public function toBigDecimal(): BigDecimal
963
    {
964
        return self::newBigDecimal($this->value);
3,900✔
965
    }
966

967
    #[Override]
968
    public function toBigRational(): BigRational
969
    {
970
        return self::newBigRational($this, BigInteger::one(), false);
393✔
971
    }
972

973
    #[Override]
974
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::UNNECESSARY): BigDecimal
975
    {
976
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
977
    }
978

979
    #[Override]
980
    public function toInt(): int
981
    {
982
        $intValue = (int) $this->value;
87✔
983

984
        if ($this->value !== (string) $intValue) {
87✔
985
            throw IntegerOverflowException::toIntOverflow($this);
15✔
986
        }
987

988
        return $intValue;
72✔
989
    }
990

991
    #[Override]
992
    public function toFloat(): float
993
    {
994
        return (float) $this->value;
48✔
995
    }
996

997
    /**
998
     * Returns a string representation of this number in the given base.
999
     *
1000
     * The output will always be lowercase for bases greater than 10.
1001
     *
1002
     * @throws InvalidArgumentException If the base is out of range.
1003
     *
1004
     * @pure
1005
     */
1006
    public function toBase(int $base): string
1007
    {
1008
        if ($base === 10) {
1,293✔
1009
            return $this->value;
12✔
1010
        }
1011

1012
        if ($base < 2 || $base > 36) {
1,281✔
1013
            throw new InvalidArgumentException(sprintf('Base %d is out of range [2, 36]', $base));
15✔
1014
        }
1015

1016
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1017
    }
1018

1019
    /**
1020
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1021
     *
1022
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers;
1023
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1024
     *
1025
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1026
     *
1027
     * @throws NegativeNumberException  If this number is negative.
1028
     * @throws InvalidArgumentException If the given alphabet does not contain at least 2 chars.
1029
     *
1030
     * @pure
1031
     */
1032
    public function toArbitraryBase(string $alphabet): string
1033
    {
1034
        $base = strlen($alphabet);
135✔
1035

1036
        if ($base < 2) {
135✔
1037
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
1038
        }
1039

1040
        if ($this->value[0] === '-') {
129✔
1041
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
3✔
1042
        }
1043

1044
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1045
    }
1046

1047
    /**
1048
     * Returns a string of bytes containing the binary representation of this BigInteger.
1049
     *
1050
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1051
     *
1052
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1053
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1054
     * number is negative.
1055
     *
1056
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1057
     * if `$signed` is true.
1058
     *
1059
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1060
     *
1061
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1062
     *
1063
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1064
     *
1065
     * @pure
1066
     */
1067
    public function toBytes(bool $signed = true): string
1068
    {
1069
        if (! $signed && $this->isNegative()) {
534✔
1070
            throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.');
3✔
1071
        }
1072

1073
        $hex = $this->abs()->toBase(16);
531✔
1074

1075
        if (strlen($hex) % 2 !== 0) {
531✔
1076
            $hex = '0' . $hex;
219✔
1077
        }
1078

1079
        $baseHexLength = strlen($hex);
531✔
1080

1081
        if ($signed) {
531✔
1082
            if ($this->isNegative()) {
492✔
1083
                $bin = hex2bin($hex);
453✔
1084
                assert($bin !== false);
1085

1086
                $hex = bin2hex(~$bin);
453✔
1087
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1088

1089
                $hexLength = strlen($hex);
453✔
1090

1091
                if ($hexLength < $baseHexLength) {
453✔
1092
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1093
                }
1094

1095
                if ($hex[0] < '8') {
453✔
1096
                    $hex = 'FF' . $hex;
114✔
1097
                }
1098
            } else {
1099
                if ($hex[0] >= '8') {
39✔
1100
                    $hex = '00' . $hex;
21✔
1101
                }
1102
            }
1103
        }
1104

1105
        $result = hex2bin($hex);
531✔
1106
        assert($result !== false);
1107

1108
        return $result;
531✔
1109
    }
1110

1111
    /**
1112
     * @return numeric-string
1113
     */
1114
    #[Override]
1115
    public function __toString(): string
1116
    {
1117
        /** @var numeric-string */
1118
        return $this->value;
12,951✔
1119
    }
1120

1121
    /**
1122
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1123
     *
1124
     * @internal
1125
     *
1126
     * @return array{value: string}
1127
     */
1128
    public function __serialize(): array
1129
    {
1130
        return ['value' => $this->value];
6✔
1131
    }
1132

1133
    /**
1134
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1135
     *
1136
     * @internal
1137
     *
1138
     * @param array{value: string} $data
1139
     *
1140
     * @throws LogicException
1141
     */
1142
    public function __unserialize(array $data): void
1143
    {
1144
        /** @phpstan-ignore isset.initializedProperty */
1145
        if (isset($this->value)) {
9✔
1146
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1147
        }
1148

1149
        /** @phpstan-ignore deadCode.unreachable */
1150
        $this->value = $data['value'];
6✔
1151
    }
1152

1153
    #[Override]
1154
    protected static function from(BigNumber $number): static
1155
    {
1156
        return $number->toBigInteger();
13,184✔
1157
    }
1158
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc