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

brick / math / 21759044472

06 Feb 2026 04:52PM UTC coverage: 98.516% (-0.7%) from 99.177%
21759044472

push

github

BenMorel
Improve NoInverseException message

1 of 1 new or added line in 1 file covered. (100.0%)

109 existing lines in 4 files now uncovered.

1328 of 1348 relevant lines covered (98.52%)

2303.56 hits per line

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

98.38
/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\InvalidArgumentException;
10
use Brick\Math\Exception\MathException;
11
use Brick\Math\Exception\NegativeNumberException;
12
use Brick\Math\Exception\NoInverseException;
13
use Brick\Math\Exception\NumberFormatException;
14
use Brick\Math\Exception\RoundingNecessaryException;
15
use Brick\Math\Internal\CalculatorRegistry;
16
use Brick\Math\Internal\Constants;
17
use LogicException;
18
use Override;
19

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

38
use const FILTER_VALIDATE_INT;
39

40
/**
41
 * An arbitrarily large integer number.
42
 *
43
 * This class is immutable.
44
 */
45
final readonly class BigInteger extends BigNumber
46
{
47
    /**
48
     * The value, as a string of digits with optional leading minus sign.
49
     *
50
     * No leading zeros must be present.
51
     * No leading minus sign must be present if the number is zero.
52
     */
53
    private string $value;
54

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

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

92
        if ($base < 2 || $base > 36) {
2,090✔
93
            throw InvalidArgumentException::baseOutOfRange($base);
15✔
94
        }
95

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

106
        if ($number === '') {
2,075✔
107
            throw NumberFormatException::emptyNumber();
6✔
108
        }
109

110
        $number = ltrim($number, '0');
2,069✔
111

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

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

122
        $pattern = '/[^' . substr(Constants::ALPHABET, 0, $base) . ']/';
1,916✔
123

124
        if (preg_match($pattern, strtolower($number), $matches) === 1) {
1,916✔
125
            throw NumberFormatException::charNotValidInBase($matches[0], $base);
111✔
126
        }
127

128
        if ($base === 10) {
1,805✔
129
            // The number is usable as is, avoid further calculation.
130
            return new BigInteger($sign . $number);
24✔
131
        }
132

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

135
        return new BigInteger($sign . $result);
1,781✔
136
    }
137

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

157
        $base = strlen($alphabet);
420✔
158

159
        if ($base < 2) {
420✔
160
            throw InvalidArgumentException::alphabetTooShort();
6✔
161
        }
162

163
        if (strlen(count_chars($alphabet, 3)) !== $base) {
414✔
164
            throw InvalidArgumentException::duplicateCharsInAlphabet();
9✔
165
        }
166

167
        $pattern = '/[^' . preg_quote($alphabet, '/') . ']/';
405✔
168

169
        if (preg_match($pattern, $number, $matches) === 1) {
405✔
170
            throw NumberFormatException::charNotInAlphabet($matches[0]);
27✔
171
        }
172

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

175
        return new BigInteger($number);
378✔
176
    }
177

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

203
        $twosComplement = false;
1,221✔
204

205
        if ($signed) {
1,221✔
206
            $x = ord($value[0]);
984✔
207

208
            if (($twosComplement = ($x >= 0x80))) {
984✔
209
                $value = ~$value;
906✔
210
            }
211
        }
212

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

215
        if ($twosComplement) {
1,221✔
216
            return $number->plus(1)->negated();
906✔
217
        }
218

219
        return $number;
315✔
220
    }
221

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

240
        if ($numBits === 0) {
162✔
241
            return BigInteger::zero();
3✔
242
        }
243

244
        if ($randomBytesGenerator === null) {
159✔
245
            $randomBytesGenerator = random_bytes(...);
×
246
        }
247

248
        /** @var int<1, max> $byteLength */
249
        $byteLength = intdiv($numBits - 1, 8) + 1;
159✔
250

251
        $extraBits = ($byteLength * 8 - $numBits);
159✔
252
        $bitmask = chr(0xFF >> $extraBits);
159✔
253

254
        $randomBytes = $randomBytesGenerator($byteLength);
159✔
255
        $randomBytes[0] = $randomBytes[0] & $bitmask;
159✔
256

257
        return self::fromBytes($randomBytes, false);
159✔
258
    }
259

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

282
        if ($min->isGreaterThan($max)) {
84✔
283
            throw InvalidArgumentException::minGreaterThanMax();
3✔
284
        }
285

286
        if ($min->isEqualTo($max)) {
81✔
287
            return $min;
3✔
288
        }
289

290
        $diff = $max->minus($min);
78✔
291
        $bitLength = $diff->getBitLength();
78✔
292

293
        // try until the number is in range (50% to 100% chance of success)
294
        do {
295
            $randomNumber = self::randomBits($bitLength, $randomBytesGenerator);
78✔
296
        } while ($randomNumber->isGreaterThan($diff));
78✔
297

298
        return $randomNumber->plus($min);
78✔
299
    }
300

301
    /**
302
     * Returns a BigInteger representing zero.
303
     *
304
     * @pure
305
     */
306
    public static function zero(): BigInteger
307
    {
308
        /** @var BigInteger|null $zero */
309
        static $zero;
222✔
310

311
        if ($zero === null) {
222✔
312
            $zero = new BigInteger('0');
×
313
        }
314

315
        return $zero;
222✔
316
    }
317

318
    /**
319
     * Returns a BigInteger representing one.
320
     *
321
     * @pure
322
     */
323
    public static function one(): BigInteger
324
    {
325
        /** @var BigInteger|null $one */
326
        static $one;
681✔
327

328
        if ($one === null) {
681✔
329
            $one = new BigInteger('1');
×
330
        }
331

332
        return $one;
681✔
333
    }
334

335
    /**
336
     * Returns a BigInteger representing ten.
337
     *
338
     * @pure
339
     */
340
    public static function ten(): BigInteger
341
    {
342
        /** @var BigInteger|null $ten */
343
        static $ten;
6✔
344

345
        if ($ten === null) {
6✔
346
            $ten = new BigInteger('10');
3✔
347
        }
348

349
        return $ten;
6✔
350
    }
351

352
    /**
353
     * @param BigNumber|int|string $a    The first number. Must be convertible to a BigInteger.
354
     * @param BigNumber|int|string ...$n The subsequent numbers. Must be convertible to BigInteger.
355
     *
356
     * @throws MathException If one of the parameters cannot be converted to a BigInteger.
357
     *
358
     * @pure
359
     */
360
    public static function gcdAll(BigNumber|int|string $a, BigNumber|int|string ...$n): BigInteger
361
    {
362
        $result = BigInteger::of($a)->abs();
1,587✔
363

364
        foreach ($n as $next) {
1,587✔
365
            $result = $result->gcd(BigInteger::of($next));
1,560✔
366

367
            if ($result->isEqualTo(1)) {
1,560✔
368
                return $result;
345✔
369
            }
370
        }
371

372
        return $result;
1,242✔
373
    }
374

375
    /**
376
     * @param BigNumber|int|string $a    The first number. Must be convertible to a BigInteger.
377
     * @param BigNumber|int|string ...$n The subsequent numbers. Must be convertible to BigInteger.
378
     *
379
     * @throws MathException If one of the parameters cannot be converted to a BigInteger.
380
     *
381
     * @pure
382
     */
383
    public static function lcmAll(BigNumber|int|string $a, BigNumber|int|string ...$n): BigInteger
384
    {
385
        $result = BigInteger::of($a)->abs();
324✔
386

387
        foreach ($n as $next) {
324✔
388
            $result = $result->lcm(BigInteger::of($next));
297✔
389

390
            if ($result->isZero()) {
297✔
391
                return $result;
51✔
392
            }
393
        }
394

395
        return $result;
273✔
396
    }
397

398
    /**
399
     * Returns the sum of this number and the given one.
400
     *
401
     * @param BigNumber|int|string $that The number to add. Must be convertible to a BigInteger.
402
     *
403
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
404
     *
405
     * @pure
406
     */
407
    public function plus(BigNumber|int|string $that): BigInteger
408
    {
409
        $that = BigInteger::of($that);
1,629✔
410

411
        if ($that->value === '0') {
1,629✔
412
            return $this;
30✔
413
        }
414

415
        if ($this->value === '0') {
1,599✔
416
            return $that;
72✔
417
        }
418

419
        $value = CalculatorRegistry::get()->add($this->value, $that->value);
1,548✔
420

421
        return new BigInteger($value);
1,548✔
422
    }
423

424
    /**
425
     * Returns the difference of this number and the given one.
426
     *
427
     * @param BigNumber|int|string $that The number to subtract. Must be convertible to a BigInteger.
428
     *
429
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
430
     *
431
     * @pure
432
     */
433
    public function minus(BigNumber|int|string $that): BigInteger
434
    {
435
        $that = BigInteger::of($that);
1,128✔
436

437
        if ($that->value === '0') {
1,128✔
438
            return $this;
84✔
439
        }
440

441
        $value = CalculatorRegistry::get()->sub($this->value, $that->value);
1,053✔
442

443
        return new BigInteger($value);
1,053✔
444
    }
445

446
    /**
447
     * Returns the product of this number and the given one.
448
     *
449
     * @param BigNumber|int|string $that The multiplier. Must be convertible to a BigInteger.
450
     *
451
     * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger.
452
     *
453
     * @pure
454
     */
455
    public function multipliedBy(BigNumber|int|string $that): BigInteger
456
    {
457
        $that = BigInteger::of($that);
1,467✔
458

459
        if ($that->value === '1') {
1,467✔
460
            return $this;
555✔
461
        }
462

463
        if ($this->value === '1') {
1,317✔
464
            return $that;
423✔
465
        }
466

467
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
1,194✔
468

469
        return new BigInteger($value);
1,194✔
470
    }
471

472
    /**
473
     * Returns the result of the division of this number by the given one.
474
     *
475
     * @param BigNumber|int|string $that         The divisor. Must be convertible to a BigInteger.
476
     * @param RoundingMode         $roundingMode An optional rounding mode, defaults to Unnecessary.
477
     *
478
     * @throws MathException              If the divisor is not a valid number or is not convertible to a BigInteger.
479
     * @throws DivisionByZeroException    If the divisor is zero.
480
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used and the remainder is not zero.
481
     *
482
     * @pure
483
     */
484
    public function dividedBy(BigNumber|int|string $that, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
485
    {
486
        $that = BigInteger::of($that);
1,977✔
487

488
        if ($that->value === '1') {
1,968✔
489
            return $this;
3✔
490
        }
491

492
        if ($that->value === '0') {
1,965✔
493
            throw DivisionByZeroException::divisionByZero();
6✔
494
        }
495

496
        $result = CalculatorRegistry::get()->divRound($this->value, $that->value, $roundingMode);
1,959✔
497

498
        if ($result === null) {
1,959✔
499
            throw RoundingNecessaryException::integerDivisionNotExact();
117✔
500
        }
501

502
        return new BigInteger($result);
1,866✔
503
    }
504

505
    /**
506
     * Returns this number exponentiated to the given value.
507
     *
508
     * @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
509
     *
510
     * @pure
511
     */
512
    public function power(int $exponent): BigInteger
513
    {
514
        if ($exponent === 0) {
1,851✔
515
            return BigInteger::one();
27✔
516
        }
517

518
        if ($exponent === 1) {
1,824✔
519
            return $this;
204✔
520
        }
521

522
        if ($exponent < 0 || $exponent > Constants::MAX_POWER) {
1,620✔
523
            throw InvalidArgumentException::exponentOutOfRange($exponent, 0, Constants::MAX_POWER);
6✔
524
        }
525

526
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,614✔
527
    }
528

529
    /**
530
     * Returns the quotient of the division of this number by the given one.
531
     *
532
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
533
     *
534
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
535
     * @throws DivisionByZeroException If the divisor is zero.
536
     *
537
     * @pure
538
     */
539
    public function quotient(BigNumber|int|string $that): BigInteger
540
    {
541
        $that = BigInteger::of($that);
2,991✔
542

543
        if ($that->value === '1') {
2,991✔
544
            return $this;
1,623✔
545
        }
546

547
        if ($that->value === '0') {
2,097✔
548
            throw DivisionByZeroException::divisionByZero();
3✔
549
        }
550

551
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
2,094✔
552

553
        return new BigInteger($quotient);
2,094✔
554
    }
555

556
    /**
557
     * Returns the remainder of the division of this number by the given one.
558
     *
559
     * The remainder, when non-zero, has the same sign as the dividend.
560
     *
561
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
562
     *
563
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
564
     * @throws DivisionByZeroException If the divisor is zero.
565
     *
566
     * @pure
567
     */
568
    public function remainder(BigNumber|int|string $that): BigInteger
569
    {
570
        $that = BigInteger::of($that);
273✔
571

572
        if ($that->value === '1') {
273✔
573
            return BigInteger::zero();
24✔
574
        }
575

576
        if ($that->value === '0') {
249✔
577
            throw DivisionByZeroException::divisionByZero();
3✔
578
        }
579

580
        $remainder = CalculatorRegistry::get()->divR($this->value, $that->value);
246✔
581

582
        return new BigInteger($remainder);
246✔
583
    }
584

585
    /**
586
     * Returns the quotient and remainder of the division of this number by the given one.
587
     *
588
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
589
     *
590
     * @return array{BigInteger, BigInteger} An array containing the quotient and the remainder.
591
     *
592
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
593
     * @throws DivisionByZeroException If the divisor is zero.
594
     *
595
     * @pure
596
     */
597
    public function quotientAndRemainder(BigNumber|int|string $that): array
598
    {
599
        $that = BigInteger::of($that);
147✔
600

601
        if ($that->value === '0') {
147✔
602
            throw DivisionByZeroException::divisionByZero();
3✔
603
        }
604

605
        [$quotient, $remainder] = CalculatorRegistry::get()->divQR($this->value, $that->value);
144✔
606

607
        return [
144✔
608
            new BigInteger($quotient),
144✔
609
            new BigInteger($remainder),
144✔
610
        ];
144✔
611
    }
612

613
    /**
614
     * Returns this number modulo the given one.
615
     *
616
     * The result is always non-negative, and is the unique value `r` such that `0 <= r < m`
617
     * and `this - r` is a multiple of `m`.
618
     *
619
     * This is also known as Euclidean modulo. Unlike `remainder()`, which can return negative values
620
     * when the dividend is negative, `mod()` always returns a non-negative result.
621
     *
622
     * Examples:
623
     *
624
     * - `7` mod `3` returns `1`
625
     * - `-7` mod `3` returns `2`
626
     *
627
     * @param BigNumber|int|string $modulus The modulus, strictly positive. Must be convertible to a BigInteger.
628
     *
629
     * @throws MathException           If the modulus is not valid, or is not convertible to a BigInteger.
630
     * @throws DivisionByZeroException If the modulus is zero.
631
     * @throws NegativeNumberException If the modulus is negative.
632
     *
633
     * @pure
634
     */
635
    public function mod(BigNumber|int|string $modulus): BigInteger
636
    {
637
        $modulus = BigInteger::of($modulus);
105✔
638

639
        if ($modulus->isZero()) {
105✔
640
            throw DivisionByZeroException::zeroModulus();
3✔
641
        }
642

643
        if ($modulus->isNegative()) {
102✔
644
            throw NegativeNumberException::negativeModulus();
3✔
645
        }
646

647
        $value = CalculatorRegistry::get()->mod($this->value, $modulus->value);
99✔
648

649
        return new BigInteger($value);
99✔
650
    }
651

652
    /**
653
     * Returns the modular multiplicative inverse of this BigInteger modulo $modulus.
654
     *
655
     * @param BigNumber|int|string $modulus The modulus. Must be convertible to a BigInteger.
656
     *
657
     * @throws DivisionByZeroException If $modulus is zero.
658
     * @throws NegativeNumberException If $modulus is negative.
659
     * @throws MathException           If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger
660
     *                                 is not relatively prime to m).
661
     *
662
     * @pure
663
     */
664
    public function modInverse(BigNumber|int|string $modulus): BigInteger
665
    {
666
        $modulus = BigInteger::of($modulus);
75✔
667

668
        if ($modulus->isZero()) {
75✔
669
            throw DivisionByZeroException::zeroModulus();
6✔
670
        }
671

672
        if ($modulus->isNegative()) {
69✔
673
            throw NegativeNumberException::negativeModulus();
3✔
674
        }
675

676
        if ($modulus->value === '1') {
66✔
677
            return BigInteger::zero();
3✔
678
        }
679

680
        $value = CalculatorRegistry::get()->modInverse($this->value, $modulus->value);
63✔
681

682
        if ($value === null) {
63✔
683
            throw NoInverseException::noModularInverse();
15✔
684
        }
685

686
        return new BigInteger($value);
48✔
687
    }
688

689
    /**
690
     * Returns this number raised into power with modulo.
691
     *
692
     * This operation requires a non-negative exponent and a strictly positive modulus.
693
     *
694
     * @param BigNumber|int|string $exponent The exponent. Must be positive or zero.
695
     * @param BigNumber|int|string $modulus  The modulus. Must be strictly positive.
696
     *
697
     * @throws MathException           If the exponent or modulus is not valid, or not convertible to a BigInteger.
698
     * @throws NegativeNumberException If the exponent or modulus is negative.
699
     * @throws DivisionByZeroException If the modulus is zero.
700
     *
701
     * @pure
702
     */
703
    public function modPow(BigNumber|int|string $exponent, BigNumber|int|string $modulus): BigInteger
704
    {
705
        $exponent = BigInteger::of($exponent);
185✔
706
        $modulus = BigInteger::of($modulus);
185✔
707

708
        if ($exponent->isNegative()) {
185✔
709
            throw NegativeNumberException::negativeExponent();
3✔
710
        }
711

712
        if ($modulus->isZero()) {
182✔
713
            throw DivisionByZeroException::zeroModulus();
3✔
714
        }
715

716
        if ($modulus->isNegative()) {
179✔
717
            throw NegativeNumberException::negativeModulus();
3✔
718
        }
719

720
        $result = CalculatorRegistry::get()->modPow($this->value, $exponent->value, $modulus->value);
176✔
721

722
        return new BigInteger($result);
176✔
723
    }
724

725
    /**
726
     * Returns the greatest common divisor of this number and the given one.
727
     *
728
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
729
     *
730
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
731
     *
732
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
733
     *
734
     * @pure
735
     */
736
    public function gcd(BigNumber|int|string $that): BigInteger
737
    {
738
        $that = BigInteger::of($that);
5,244✔
739

740
        if ($that->value === '0' && $this->value[0] !== '-') {
5,244✔
741
            return $this;
66✔
742
        }
743

744
        if ($this->value === '0' && $that->value[0] !== '-') {
5,178✔
745
            return $that;
393✔
746
        }
747

748
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
5,055✔
749

750
        return new BigInteger($value);
5,055✔
751
    }
752

753
    /**
754
     * Returns the least common multiple of this number and the given one.
755
     *
756
     * The LCM is always positive, unless at least one operand is zero, in which case it is zero.
757
     *
758
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
759
     *
760
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
761
     *
762
     * @pure
763
     */
764
    public function lcm(BigNumber|int|string $that): BigInteger
765
    {
766
        $that = BigInteger::of($that);
561✔
767

768
        if ($this->isZero() || $that->isZero()) {
561✔
769
            return BigInteger::zero();
99✔
770
        }
771

772
        $value = CalculatorRegistry::get()->lcm($this->value, $that->value);
462✔
773

774
        return new BigInteger($value);
462✔
775
    }
776

777
    /**
778
     * Returns the integer square root of this number, rounded according to the given rounding mode.
779
     *
780
     * @param RoundingMode $roundingMode The rounding mode to use, defaults to Unnecessary.
781
     *
782
     * @throws NegativeNumberException    If this number is negative.
783
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and the number is not a perfect square.
784
     *
785
     * @pure
786
     */
787
    public function sqrt(RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
788
    {
789
        if ($this->value[0] === '-') {
10,623✔
790
            throw NegativeNumberException::squareRootOfNegativeNumber();
3✔
791
        }
792

793
        $calculator = CalculatorRegistry::get();
10,620✔
794

795
        $sqrt = $calculator->sqrt($this->value);
10,620✔
796

797
        // For Down and Floor (equivalent for non-negative numbers), return floor sqrt
798
        if ($roundingMode === RoundingMode::Down || $roundingMode === RoundingMode::Floor) {
10,620✔
799
            return new BigInteger($sqrt);
2,130✔
800
        }
801

802
        // Check if the sqrt is exact
803
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
804
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
805

806
        if ($remainder === '0') {
8,490✔
807
            // sqrt is exact
808
            return new BigInteger($sqrt);
5,385✔
809
        }
810

811
        // sqrt is not exact
812
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
813
            throw RoundingNecessaryException::integerSquareRootNotExact();
390✔
814
        }
815

816
        // For Up and Ceiling (equivalent for non-negative numbers), round up
817
        if ($roundingMode === RoundingMode::Up || $roundingMode === RoundingMode::Ceiling) {
2,715✔
818
            return new BigInteger($calculator->add($sqrt, '1'));
780✔
819
        }
820

821
        // For Half* modes, compare our number to the midpoint of the interval [s², (s+1)²[.
822
        // The midpoint is s² + s + 0.5. Comparing n >= s² + s + 0.5 with remainder = n − s²
823
        // is equivalent to comparing 2*remainder >= 2*s + 1.
824
        $twoRemainder = $calculator->mul($remainder, '2');
1,935✔
825
        $threshold = $calculator->add($calculator->mul($sqrt, '2'), '1');
1,935✔
826
        $cmp = $calculator->cmp($twoRemainder, $threshold);
1,935✔
827

828
        // We're supposed to increment (round up) when:
829
        //   - HalfUp, HalfCeiling => $cmp >= 0
830
        //   - HalfDown, HalfFloor => $cmp > 0
831
        //   - HalfEven => $cmp > 0 || ($cmp === 0 && $sqrt % 2 === 1)
832
        // But 2*remainder is always even and 2*s + 1 is always odd, so $cmp is never zero.
833
        // Therefore, all Half* modes simplify to:
834
        if ($cmp > 0) {
1,935✔
835
            $sqrt = $calculator->add($sqrt, '1');
990✔
836
        }
837

838
        return new BigInteger($sqrt);
1,935✔
839
    }
840

841
    #[Override]
842
    public function negated(): static
843
    {
844
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,798✔
845
    }
846

847
    /**
848
     * Returns the integer bitwise-and combined with another integer.
849
     *
850
     * This method returns a negative BigInteger if and only if both operands are negative.
851
     *
852
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
853
     *
854
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
855
     *
856
     * @pure
857
     */
858
    public function and(BigNumber|int|string $that): BigInteger
859
    {
860
        $that = BigInteger::of($that);
153✔
861

862
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
863
    }
864

865
    /**
866
     * Returns the integer bitwise-or combined with another integer.
867
     *
868
     * This method returns a negative BigInteger if and only if either of the operands is negative.
869
     *
870
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
871
     *
872
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
873
     *
874
     * @pure
875
     */
876
    public function or(BigNumber|int|string $that): BigInteger
877
    {
878
        $that = BigInteger::of($that);
138✔
879

880
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
881
    }
882

883
    /**
884
     * Returns the integer bitwise-xor combined with another integer.
885
     *
886
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
887
     *
888
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
889
     *
890
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
891
     *
892
     * @pure
893
     */
894
    public function xor(BigNumber|int|string $that): BigInteger
895
    {
896
        $that = BigInteger::of($that);
144✔
897

898
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
899
    }
900

901
    /**
902
     * Returns the bitwise-not of this BigInteger.
903
     *
904
     * @pure
905
     */
906
    public function not(): BigInteger
907
    {
908
        return $this->negated()->minus(1);
57✔
909
    }
910

911
    /**
912
     * Returns the integer left shifted by a given number of bits.
913
     *
914
     * @throws InvalidArgumentException If the number of bits is out of range.
915
     *
916
     * @pure
917
     */
918
    public function shiftedLeft(int $bits): BigInteger
919
    {
920
        if ($bits === 0) {
594✔
921
            return $this;
6✔
922
        }
923

924
        if ($bits > Constants::MAX_BIT_SHIFT || $bits < -Constants::MAX_BIT_SHIFT) {
588✔
UNCOV
925
            throw InvalidArgumentException::bitShiftOutOfRange($bits);
×
926
        }
927

928
        if ($bits < 0) {
588✔
929
            return $this->shiftedRight(-$bits);
198✔
930
        }
931

932
        return $this->multipliedBy(BigInteger::of(2)->power($bits));
390✔
933
    }
934

935
    /**
936
     * Returns the integer right shifted by a given number of bits.
937
     *
938
     * @throws InvalidArgumentException If the number of bits is out of range.
939
     *
940
     * @pure
941
     */
942
    public function shiftedRight(int $bits): BigInteger
943
    {
944
        if ($bits === 0) {
1,518✔
945
            return $this;
66✔
946
        }
947

948
        if ($bits > Constants::MAX_BIT_SHIFT || $bits < -Constants::MAX_BIT_SHIFT) {
1,452✔
UNCOV
949
            throw InvalidArgumentException::bitShiftOutOfRange($bits);
×
950
        }
951

952
        if ($bits < 0) {
1,452✔
953
            return $this->shiftedLeft(-$bits);
195✔
954
        }
955

956
        $operand = BigInteger::of(2)->power($bits);
1,257✔
957

958
        if ($this->isPositiveOrZero()) {
1,257✔
959
            return $this->quotient($operand);
672✔
960
        }
961

962
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
963
    }
964

965
    /**
966
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
967
     *
968
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
969
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
970
     *
971
     * @pure
972
     */
973
    public function getBitLength(): int
974
    {
975
        if ($this->value === '0') {
321✔
976
            return 0;
12✔
977
        }
978

979
        if ($this->isNegative()) {
315✔
980
            return $this->abs()->minus(1)->getBitLength();
120✔
981
        }
982

983
        return strlen($this->toBase(2));
309✔
984
    }
985

986
    /**
987
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
988
     *
989
     * Returns -1 if this BigInteger contains no one bits.
990
     *
991
     * @pure
992
     */
993
    public function getLowestSetBit(): int
994
    {
995
        $n = $this;
81✔
996
        $bitLength = $this->getBitLength();
81✔
997

998
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
999
            if ($n->isOdd()) {
81✔
1000
                return $i;
78✔
1001
            }
1002

1003
            $n = $n->shiftedRight(1);
51✔
1004
        }
1005

1006
        return -1;
3✔
1007
    }
1008

1009
    /**
1010
     * Returns whether this number is even.
1011
     *
1012
     * @pure
1013
     */
1014
    public function isEven(): bool
1015
    {
1016
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
1017
    }
1018

1019
    /**
1020
     * Returns whether this number is odd.
1021
     *
1022
     * @pure
1023
     */
1024
    public function isOdd(): bool
1025
    {
1026
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
1027
    }
1028

1029
    /**
1030
     * Returns true if and only if the designated bit is set.
1031
     *
1032
     * Computes ((this & (1<<n)) != 0).
1033
     *
1034
     * @param int $n The bit to test, 0-based.
1035
     *
1036
     * @throws InvalidArgumentException If the bit to test is negative.
1037
     *
1038
     * @pure
1039
     */
1040
    public function testBit(int $n): bool
1041
    {
1042
        if ($n < 0) {
873✔
1043
            throw InvalidArgumentException::negativeBitIndex();
3✔
1044
        }
1045

1046
        return $this->shiftedRight($n)->isOdd();
870✔
1047
    }
1048

1049
    #[Override]
1050
    public function compareTo(BigNumber|int|string $that): int
1051
    {
1052
        $that = BigNumber::of($that);
2,366✔
1053

1054
        if ($that instanceof BigInteger) {
2,366✔
1055
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,258✔
1056
        }
1057

1058
        return -$that->compareTo($this);
108✔
1059
    }
1060

1061
    #[Override]
1062
    public function getSign(): int
1063
    {
1064
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
6,029✔
1065
    }
1066

1067
    #[Override]
1068
    public function toBigInteger(): BigInteger
1069
    {
1070
        return $this;
24,755✔
1071
    }
1072

1073
    #[Override]
1074
    public function toBigDecimal(): BigDecimal
1075
    {
1076
        return self::newBigDecimal($this->value);
4,941✔
1077
    }
1078

1079
    #[Override]
1080
    public function toBigRational(): BigRational
1081
    {
1082
        return self::newBigRational($this, BigInteger::one(), false, false);
639✔
1083
    }
1084

1085
    #[Override]
1086
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1087
    {
1088
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1089
    }
1090

1091
    #[Override]
1092
    public function toInt(): int
1093
    {
1094
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1095

1096
        if ($intValue === false) {
87✔
1097
            throw IntegerOverflowException::integerOutOfRange($this);
15✔
1098
        }
1099

1100
        return $intValue;
72✔
1101
    }
1102

1103
    #[Override]
1104
    public function toFloat(): float
1105
    {
1106
        return (float) $this->value;
183✔
1107
    }
1108

1109
    /**
1110
     * Returns a string representation of this number in the given base.
1111
     *
1112
     * The output will always be lowercase for bases greater than 10.
1113
     *
1114
     * @throws InvalidArgumentException If the base is out of range.
1115
     *
1116
     * @pure
1117
     */
1118
    public function toBase(int $base): string
1119
    {
1120
        if ($base === 10) {
1,293✔
1121
            return $this->value;
12✔
1122
        }
1123

1124
        if ($base < 2 || $base > 36) {
1,281✔
1125
            throw InvalidArgumentException::baseOutOfRange($base);
15✔
1126
        }
1127

1128
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1129
    }
1130

1131
    /**
1132
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1133
     *
1134
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers;
1135
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1136
     *
1137
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1138
     *
1139
     * @throws NegativeNumberException  If this number is negative.
1140
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
1141
     *
1142
     * @pure
1143
     */
1144
    public function toArbitraryBase(string $alphabet): string
1145
    {
1146
        $base = strlen($alphabet);
144✔
1147

1148
        if ($base < 2) {
144✔
1149
            throw InvalidArgumentException::alphabetTooShort();
6✔
1150
        }
1151

1152
        if (strlen(count_chars($alphabet, 3)) !== $base) {
138✔
1153
            throw InvalidArgumentException::duplicateCharsInAlphabet();
9✔
1154
        }
1155

1156
        if ($this->value[0] === '-') {
129✔
1157
            throw NegativeNumberException::notSupportedForNegativeNumber(__FUNCTION__);
3✔
1158
        }
1159

1160
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1161
    }
1162

1163
    /**
1164
     * Returns a string of bytes containing the binary representation of this BigInteger.
1165
     *
1166
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1167
     *
1168
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1169
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1170
     * number is negative.
1171
     *
1172
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1173
     * if `$signed` is true.
1174
     *
1175
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1176
     *
1177
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1178
     *
1179
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1180
     *
1181
     * @pure
1182
     */
1183
    public function toBytes(bool $signed = true): string
1184
    {
1185
        if (! $signed && $this->isNegative()) {
534✔
1186
            throw NegativeNumberException::unsignedBytesOfNegativeNumber();
3✔
1187
        }
1188

1189
        $hex = $this->abs()->toBase(16);
531✔
1190

1191
        if (strlen($hex) % 2 !== 0) {
531✔
1192
            $hex = '0' . $hex;
219✔
1193
        }
1194

1195
        $baseHexLength = strlen($hex);
531✔
1196

1197
        if ($signed) {
531✔
1198
            if ($this->isNegative()) {
492✔
1199
                $bin = hex2bin($hex);
453✔
1200
                assert($bin !== false);
1201

1202
                $hex = bin2hex(~$bin);
453✔
1203
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1204

1205
                $hexLength = strlen($hex);
453✔
1206

1207
                if ($hexLength < $baseHexLength) {
453✔
1208
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1209
                }
1210

1211
                if ($hex[0] < '8') {
453✔
1212
                    $hex = 'FF' . $hex;
114✔
1213
                }
1214
            } else {
1215
                if ($hex[0] >= '8') {
39✔
1216
                    $hex = '00' . $hex;
21✔
1217
                }
1218
            }
1219
        }
1220

1221
        $result = hex2bin($hex);
531✔
1222
        assert($result !== false);
1223

1224
        return $result;
531✔
1225
    }
1226

1227
    /**
1228
     * @return numeric-string
1229
     */
1230
    #[Override]
1231
    public function toString(): string
1232
    {
1233
        /** @var numeric-string */
1234
        return $this->value;
24,354✔
1235
    }
1236

1237
    /**
1238
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1239
     *
1240
     * @internal
1241
     *
1242
     * @return array{value: string}
1243
     */
1244
    public function __serialize(): array
1245
    {
1246
        return ['value' => $this->value];
6✔
1247
    }
1248

1249
    /**
1250
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1251
     *
1252
     * @internal
1253
     *
1254
     * @param array{value: string} $data
1255
     *
1256
     * @throws LogicException
1257
     */
1258
    public function __unserialize(array $data): void
1259
    {
1260
        /** @phpstan-ignore isset.initializedProperty */
1261
        if (isset($this->value)) {
9✔
1262
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1263
        }
1264

1265
        /** @phpstan-ignore deadCode.unreachable */
1266
        $this->value = $data['value'];
6✔
1267
    }
1268

1269
    #[Override]
1270
    protected static function from(BigNumber $number): static
1271
    {
1272
        return $number->toBigInteger();
24,857✔
1273
    }
1274
}
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