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

brick / math / 21716645310

05 Feb 2026 03:05PM UTC coverage: 99.369% (+0.01%) from 99.357%
21716645310

push

github

BenMorel
Clearer CHANGELOG

1260 of 1268 relevant lines covered (99.37%)

2502.36 hits per line

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

99.01
/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\Calculator;
16
use Brick\Math\Internal\CalculatorRegistry;
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,274✔
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(Calculator::ALPHABET, 0, $base) . ']/';
1,916✔
123

124
        if (preg_match($pattern, strtolower($number), $matches) === 1) {
1,916✔
125
            throw NumberFormatException::charNotInBase($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;
528✔
327

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

332
        return $one;
528✔
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);
990✔
436

437
        if ($that->value === '0') {
990✔
438
            return $this;
30✔
439
        }
440

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

443
        return new BigInteger($value);
969✔
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,332✔
458

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

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

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

469
        return new BigInteger($value);
1,158✔
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
        return new BigInteger($result);
1,866✔
499
    }
500

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

514
        if ($exponent === 1) {
1,824✔
515
            return $this;
204✔
516
        }
517

518
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
1,620✔
519
            throw InvalidArgumentException::exponentOutOfRange($exponent, 0, Calculator::MAX_POWER);
6✔
520
        }
521

522
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,614✔
523
    }
524

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

539
        if ($that->value === '1') {
2,832✔
540
            return $this;
1,473✔
541
        }
542

543
        if ($that->value === '0') {
1,950✔
544
            throw DivisionByZeroException::divisionByZero();
3✔
545
        }
546

547
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
1,947✔
548

549
        return new BigInteger($quotient);
1,947✔
550
    }
551

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

568
        if ($that->value === '1') {
273✔
569
            return BigInteger::zero();
24✔
570
        }
571

572
        if ($that->value === '0') {
249✔
573
            throw DivisionByZeroException::divisionByZero();
3✔
574
        }
575

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

578
        return new BigInteger($remainder);
246✔
579
    }
580

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

597
        if ($that->value === '0') {
147✔
598
            throw DivisionByZeroException::divisionByZero();
3✔
599
        }
600

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

603
        return [
144✔
604
            new BigInteger($quotient),
144✔
605
            new BigInteger($remainder),
144✔
606
        ];
144✔
607
    }
608

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

635
        if ($modulus->isZero()) {
105✔
636
            throw DivisionByZeroException::zeroModulus();
3✔
637
        }
638

639
        if ($modulus->isNegative()) {
102✔
640
            throw NegativeNumberException::negativeModulus();
3✔
641
        }
642

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

645
        return new BigInteger($value);
99✔
646
    }
647

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

664
        if ($modulus->isZero()) {
75✔
665
            throw DivisionByZeroException::zeroModulus();
6✔
666
        }
667

668
        if ($modulus->isNegative()) {
69✔
669
            throw NegativeNumberException::negativeModulus();
3✔
670
        }
671

672
        if ($modulus->value === '1') {
66✔
673
            return BigInteger::zero();
3✔
674
        }
675

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

678
        if ($value === null) {
63✔
679
            throw NoInverseException::noModularInverse();
15✔
680
        }
681

682
        return new BigInteger($value);
48✔
683
    }
684

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

704
        if ($exponent->isNegative()) {
185✔
705
            throw NegativeNumberException::negativeExponent();
3✔
706
        }
707

708
        if ($modulus->isZero()) {
182✔
709
            throw DivisionByZeroException::zeroModulus();
3✔
710
        }
711

712
        if ($modulus->isNegative()) {
179✔
713
            throw NegativeNumberException::negativeModulus();
3✔
714
        }
715

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

718
        return new BigInteger($result);
176✔
719
    }
720

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

736
        if ($that->value === '0' && $this->value[0] !== '-') {
5,085✔
737
            return $this;
66✔
738
        }
739

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

744
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
4,923✔
745

746
        return new BigInteger($value);
4,923✔
747
    }
748

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

764
        if ($this->isZero() || $that->isZero()) {
561✔
765
            return BigInteger::zero();
99✔
766
        }
767

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

770
        return new BigInteger($value);
462✔
771
    }
772

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

789
        $calculator = CalculatorRegistry::get();
10,620✔
790

791
        $sqrt = $calculator->sqrt($this->value);
10,620✔
792

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

798
        // Check if the sqrt is exact
799
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
800
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
801

802
        if ($remainder === '0') {
8,490✔
803
            // sqrt is exact
804
            return new BigInteger($sqrt);
5,385✔
805
        }
806

807
        // sqrt is not exact
808
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
809
            throw RoundingNecessaryException::roundingNecessary();
390✔
810
        }
811

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

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

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

834
        return new BigInteger($sqrt);
1,935✔
835
    }
836

837
    #[Override]
838
    public function negated(): static
839
    {
840
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,798✔
841
    }
842

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

858
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
859
    }
860

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

876
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
877
    }
878

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

894
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
895
    }
896

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

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

920
        if ($bits < 0) {
588✔
921
            return $this->shiftedRight(-$bits);
198✔
922
        }
923

924
        return $this->multipliedBy(BigInteger::of(2)->power($bits));
390✔
925
    }
926

927
    /**
928
     * Returns the integer right shifted by a given number of bits.
929
     *
930
     * @throws InvalidArgumentException If the number of bits is out of range.
931
     *
932
     * @pure
933
     */
934
    public function shiftedRight(int $bits): BigInteger
935
    {
936
        if ($bits === 0) {
1,518✔
937
            return $this;
66✔
938
        }
939

940
        if ($bits < 0) {
1,452✔
941
            return $this->shiftedLeft(-$bits);
195✔
942
        }
943

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

946
        if ($this->isPositiveOrZero()) {
1,257✔
947
            return $this->quotient($operand);
672✔
948
        }
949

950
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
951
    }
952

953
    /**
954
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
955
     *
956
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
957
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
958
     *
959
     * @pure
960
     */
961
    public function getBitLength(): int
962
    {
963
        if ($this->value === '0') {
321✔
964
            return 0;
12✔
965
        }
966

967
        if ($this->isNegative()) {
315✔
968
            return $this->abs()->minus(1)->getBitLength();
120✔
969
        }
970

971
        return strlen($this->toBase(2));
309✔
972
    }
973

974
    /**
975
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
976
     *
977
     * Returns -1 if this BigInteger contains no one bits.
978
     *
979
     * @pure
980
     */
981
    public function getLowestSetBit(): int
982
    {
983
        $n = $this;
81✔
984
        $bitLength = $this->getBitLength();
81✔
985

986
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
987
            if ($n->isOdd()) {
81✔
988
                return $i;
78✔
989
            }
990

991
            $n = $n->shiftedRight(1);
51✔
992
        }
993

994
        return -1;
3✔
995
    }
996

997
    /**
998
     * Returns whether this number is even.
999
     *
1000
     * @pure
1001
     */
1002
    public function isEven(): bool
1003
    {
1004
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
1005
    }
1006

1007
    /**
1008
     * Returns whether this number is odd.
1009
     *
1010
     * @pure
1011
     */
1012
    public function isOdd(): bool
1013
    {
1014
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
1015
    }
1016

1017
    /**
1018
     * Returns true if and only if the designated bit is set.
1019
     *
1020
     * Computes ((this & (1<<n)) != 0).
1021
     *
1022
     * @param int $n The bit to test, 0-based.
1023
     *
1024
     * @throws InvalidArgumentException If the bit to test is negative.
1025
     *
1026
     * @pure
1027
     */
1028
    public function testBit(int $n): bool
1029
    {
1030
        if ($n < 0) {
873✔
1031
            throw InvalidArgumentException::negativeBitIndex();
3✔
1032
        }
1033

1034
        return $this->shiftedRight($n)->isOdd();
870✔
1035
    }
1036

1037
    #[Override]
1038
    public function compareTo(BigNumber|int|string $that): int
1039
    {
1040
        $that = BigNumber::of($that);
2,327✔
1041

1042
        if ($that instanceof BigInteger) {
2,327✔
1043
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,219✔
1044
        }
1045

1046
        return -$that->compareTo($this);
108✔
1047
    }
1048

1049
    #[Override]
1050
    public function getSign(): int
1051
    {
1052
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
5,894✔
1053
    }
1054

1055
    #[Override]
1056
    public function toBigInteger(): BigInteger
1057
    {
1058
        return $this;
24,632✔
1059
    }
1060

1061
    #[Override]
1062
    public function toBigDecimal(): BigDecimal
1063
    {
1064
        return self::newBigDecimal($this->value);
5,223✔
1065
    }
1066

1067
    #[Override]
1068
    public function toBigRational(): BigRational
1069
    {
1070
        return self::newBigRational($this, BigInteger::one(), false, false);
486✔
1071
    }
1072

1073
    #[Override]
1074
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1075
    {
1076
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1077
    }
1078

1079
    #[Override]
1080
    public function toInt(): int
1081
    {
1082
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1083

1084
        if ($intValue === false) {
87✔
1085
            throw IntegerOverflowException::integerOverflow($this);
15✔
1086
        }
1087

1088
        return $intValue;
72✔
1089
    }
1090

1091
    #[Override]
1092
    public function toFloat(): float
1093
    {
1094
        return (float) $this->value;
183✔
1095
    }
1096

1097
    /**
1098
     * Returns a string representation of this number in the given base.
1099
     *
1100
     * The output will always be lowercase for bases greater than 10.
1101
     *
1102
     * @throws InvalidArgumentException If the base is out of range.
1103
     *
1104
     * @pure
1105
     */
1106
    public function toBase(int $base): string
1107
    {
1108
        if ($base === 10) {
1,293✔
1109
            return $this->value;
12✔
1110
        }
1111

1112
        if ($base < 2 || $base > 36) {
1,281✔
1113
            throw InvalidArgumentException::baseOutOfRange($base);
15✔
1114
        }
1115

1116
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1117
    }
1118

1119
    /**
1120
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1121
     *
1122
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers;
1123
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1124
     *
1125
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1126
     *
1127
     * @throws NegativeNumberException  If this number is negative.
1128
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
1129
     *
1130
     * @pure
1131
     */
1132
    public function toArbitraryBase(string $alphabet): string
1133
    {
1134
        $base = strlen($alphabet);
144✔
1135

1136
        if ($base < 2) {
144✔
1137
            throw InvalidArgumentException::alphabetTooShort();
6✔
1138
        }
1139

1140
        if (strlen(count_chars($alphabet, 3)) !== $base) {
138✔
1141
            throw InvalidArgumentException::duplicateCharsInAlphabet();
9✔
1142
        }
1143

1144
        if ($this->value[0] === '-') {
129✔
1145
            throw NegativeNumberException::notSupportedForNegativeNumber(__FUNCTION__);
3✔
1146
        }
1147

1148
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1149
    }
1150

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

1177
        $hex = $this->abs()->toBase(16);
531✔
1178

1179
        if (strlen($hex) % 2 !== 0) {
531✔
1180
            $hex = '0' . $hex;
219✔
1181
        }
1182

1183
        $baseHexLength = strlen($hex);
531✔
1184

1185
        if ($signed) {
531✔
1186
            if ($this->isNegative()) {
492✔
1187
                $bin = hex2bin($hex);
453✔
1188
                assert($bin !== false);
1189

1190
                $hex = bin2hex(~$bin);
453✔
1191
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1192

1193
                $hexLength = strlen($hex);
453✔
1194

1195
                if ($hexLength < $baseHexLength) {
453✔
1196
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1197
                }
1198

1199
                if ($hex[0] < '8') {
453✔
1200
                    $hex = 'FF' . $hex;
114✔
1201
                }
1202
            } else {
1203
                if ($hex[0] >= '8') {
39✔
1204
                    $hex = '00' . $hex;
21✔
1205
                }
1206
            }
1207
        }
1208

1209
        $result = hex2bin($hex);
531✔
1210
        assert($result !== false);
1211

1212
        return $result;
531✔
1213
    }
1214

1215
    /**
1216
     * @return numeric-string
1217
     */
1218
    #[Override]
1219
    public function toString(): string
1220
    {
1221
        /** @var numeric-string */
1222
        return $this->value;
23,799✔
1223
    }
1224

1225
    /**
1226
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1227
     *
1228
     * @internal
1229
     *
1230
     * @return array{value: string}
1231
     */
1232
    public function __serialize(): array
1233
    {
1234
        return ['value' => $this->value];
6✔
1235
    }
1236

1237
    /**
1238
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1239
     *
1240
     * @internal
1241
     *
1242
     * @param array{value: string} $data
1243
     *
1244
     * @throws LogicException
1245
     */
1246
    public function __unserialize(array $data): void
1247
    {
1248
        /** @phpstan-ignore isset.initializedProperty */
1249
        if (isset($this->value)) {
9✔
1250
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1251
        }
1252

1253
        /** @phpstan-ignore deadCode.unreachable */
1254
        $this->value = $data['value'];
6✔
1255
    }
1256

1257
    #[Override]
1258
    protected static function from(BigNumber $number): static
1259
    {
1260
        return $number->toBigInteger();
24,770✔
1261
    }
1262
}
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