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

brick / math / 21718170057

05 Feb 2026 03:47PM UTC coverage: 99.37%. Remained the same
21718170057

push

github

BenMorel
Minor documentation tweaks

1261 of 1269 relevant lines covered (99.37%)

2501.11 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,271✔
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::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
     * This method is byte-oriented: the alphabet is interpreted as a sequence of single-byte characters.
142
     * Multibyte UTF-8 characters are not supported.
143
     *
144
     * Because this method accepts any single-byte character, including dash, it does not handle negative numbers.
145
     *
146
     * @param string $number   The number to parse.
147
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
148
     *
149
     * @throws NumberFormatException    If the given number is empty or contains invalid chars for the given alphabet.
150
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
151
     *
152
     * @pure
153
     */
154
    public static function fromArbitraryBase(string $number, string $alphabet): BigInteger
155
    {
156
        if ($number === '') {
423✔
157
            throw NumberFormatException::emptyNumber();
3✔
158
        }
159

160
        $base = strlen($alphabet);
420✔
161

162
        if ($base < 2) {
420✔
163
            throw InvalidArgumentException::alphabetTooShort();
6✔
164
        }
165

166
        if (strlen(count_chars($alphabet, 3)) !== $base) {
414✔
167
            throw InvalidArgumentException::duplicateCharsInAlphabet();
9✔
168
        }
169

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

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

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

178
        return new BigInteger($number);
378✔
179
    }
180

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

206
        $twosComplement = false;
1,221✔
207

208
        if ($signed) {
1,221✔
209
            $x = ord($value[0]);
984✔
210

211
            if (($twosComplement = ($x >= 0x80))) {
984✔
212
                $value = ~$value;
906✔
213
            }
214
        }
215

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

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

222
        return $number;
315✔
223
    }
224

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

243
        if ($numBits === 0) {
162✔
244
            return BigInteger::zero();
3✔
245
        }
246

247
        if ($randomBytesGenerator === null) {
159✔
248
            $randomBytesGenerator = random_bytes(...);
×
249
        }
250

251
        /** @var int<1, max> $byteLength */
252
        $byteLength = intdiv($numBits - 1, 8) + 1;
159✔
253

254
        $extraBits = ($byteLength * 8 - $numBits);
159✔
255
        $bitmask = chr(0xFF >> $extraBits);
159✔
256

257
        $randomBytes = $randomBytesGenerator($byteLength);
159✔
258
        $randomBytes[0] = $randomBytes[0] & $bitmask;
159✔
259

260
        return self::fromBytes($randomBytes, false);
159✔
261
    }
262

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

285
        if ($min->isGreaterThan($max)) {
84✔
286
            throw InvalidArgumentException::minGreaterThanMax();
3✔
287
        }
288

289
        if ($min->isEqualTo($max)) {
81✔
290
            return $min;
3✔
291
        }
292

293
        $diff = $max->minus($min);
78✔
294
        $bitLength = $diff->getBitLength();
78✔
295

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

301
        return $randomNumber->plus($min);
78✔
302
    }
303

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

314
        if ($zero === null) {
222✔
315
            $zero = new BigInteger('0');
×
316
        }
317

318
        return $zero;
222✔
319
    }
320

321
    /**
322
     * Returns a BigInteger representing one.
323
     *
324
     * @pure
325
     */
326
    public static function one(): BigInteger
327
    {
328
        /** @var BigInteger|null $one */
329
        static $one;
519✔
330

331
        if ($one === null) {
519✔
332
            $one = new BigInteger('1');
×
333
        }
334

335
        return $one;
519✔
336
    }
337

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

348
        if ($ten === null) {
6✔
349
            $ten = new BigInteger('10');
3✔
350
        }
351

352
        return $ten;
6✔
353
    }
354

355
    /**
356
     * Returns the greatest common divisor of the given numbers.
357
     *
358
     * The GCD is always positive, unless all numbers are zero, in which case it is zero.
359
     *
360
     * @param BigNumber|int|string $a    The first number. Must be convertible to a BigInteger.
361
     * @param BigNumber|int|string ...$n The subsequent numbers. Must be convertible to BigInteger.
362
     *
363
     * @throws MathException If one of the parameters cannot be converted to a BigInteger.
364
     *
365
     * @pure
366
     */
367
    public static function gcdAll(BigNumber|int|string $a, BigNumber|int|string ...$n): BigInteger
368
    {
369
        $result = BigInteger::of($a)->abs();
1,587✔
370

371
        foreach ($n as $next) {
1,587✔
372
            $result = $result->gcd(BigInteger::of($next));
1,560✔
373

374
            if ($result->isEqualTo(1)) {
1,560✔
375
                return $result;
345✔
376
            }
377
        }
378

379
        return $result;
1,242✔
380
    }
381

382
    /**
383
     * Returns the least common multiple of the given numbers.
384
     *
385
     * The LCM is always positive, unless one of the numbers is zero, in which case it is zero.
386
     *
387
     * @param BigNumber|int|string $a    The first number. Must be convertible to a BigInteger.
388
     * @param BigNumber|int|string ...$n The subsequent numbers. Must be convertible to BigInteger.
389
     *
390
     * @throws MathException If one of the parameters cannot be converted to a BigInteger.
391
     *
392
     * @pure
393
     */
394
    public static function lcmAll(BigNumber|int|string $a, BigNumber|int|string ...$n): BigInteger
395
    {
396
        $result = BigInteger::of($a)->abs();
324✔
397

398
        foreach ($n as $next) {
324✔
399
            $result = $result->lcm(BigInteger::of($next));
297✔
400

401
            if ($result->isZero()) {
297✔
402
                return $result;
51✔
403
            }
404
        }
405

406
        return $result;
273✔
407
    }
408

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

422
        if ($that->value === '0') {
1,629✔
423
            return $this;
30✔
424
        }
425

426
        if ($this->value === '0') {
1,599✔
427
            return $that;
72✔
428
        }
429

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

432
        return new BigInteger($value);
1,548✔
433
    }
434

435
    /**
436
     * Returns the difference of this number and the given one.
437
     *
438
     * @param BigNumber|int|string $that The number to subtract. Must be convertible to a BigInteger.
439
     *
440
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
441
     *
442
     * @pure
443
     */
444
    public function minus(BigNumber|int|string $that): BigInteger
445
    {
446
        $that = BigInteger::of($that);
990✔
447

448
        if ($that->value === '0') {
990✔
449
            return $this;
30✔
450
        }
451

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

454
        return new BigInteger($value);
969✔
455
    }
456

457
    /**
458
     * Returns the product of this number and the given one.
459
     *
460
     * @param BigNumber|int|string $that The multiplier. Must be convertible to a BigInteger.
461
     *
462
     * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger.
463
     *
464
     * @pure
465
     */
466
    public function multipliedBy(BigNumber|int|string $that): BigInteger
467
    {
468
        $that = BigInteger::of($that);
1,332✔
469

470
        if ($that->value === '1') {
1,332✔
471
            return $this;
417✔
472
        }
473

474
        if ($this->value === '1') {
1,266✔
475
            return $that;
408✔
476
        }
477

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

480
        return new BigInteger($value);
1,158✔
481
    }
482

483
    /**
484
     * Returns the result of the division of this number by the given one.
485
     *
486
     * @param BigNumber|int|string $that         The divisor. Must be convertible to a BigInteger.
487
     * @param RoundingMode         $roundingMode An optional rounding mode, defaults to Unnecessary.
488
     *
489
     * @throws MathException              If the divisor is not a valid number or is not convertible to a BigInteger.
490
     * @throws DivisionByZeroException    If the divisor is zero.
491
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used and the remainder is not zero.
492
     *
493
     * @pure
494
     */
495
    public function dividedBy(BigNumber|int|string $that, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
496
    {
497
        $that = BigInteger::of($that);
1,977✔
498

499
        if ($that->value === '1') {
1,968✔
500
            return $this;
3✔
501
        }
502

503
        if ($that->value === '0') {
1,965✔
504
            throw DivisionByZeroException::divisionByZero();
6✔
505
        }
506

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

509
        return new BigInteger($result);
1,866✔
510
    }
511

512
    /**
513
     * Returns this number exponentiated to the given value.
514
     *
515
     * @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
516
     *
517
     * @pure
518
     */
519
    public function power(int $exponent): BigInteger
520
    {
521
        if ($exponent === 0) {
1,851✔
522
            return BigInteger::one();
27✔
523
        }
524

525
        if ($exponent === 1) {
1,824✔
526
            return $this;
204✔
527
        }
528

529
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
1,620✔
530
            throw InvalidArgumentException::exponentOutOfRange($exponent, 0, Calculator::MAX_POWER);
6✔
531
        }
532

533
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,614✔
534
    }
535

536
    /**
537
     * Returns the quotient of the division of this number by the given one.
538
     *
539
     * Examples:
540
     *
541
     * - `7` quotient `3` returns `2`
542
     * - `7` quotient `-3` returns `-2`
543
     * - `-7` quotient `3` returns `-2`
544
     * - `-7` quotient `-3` returns `2`
545
     *
546
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
547
     *
548
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
549
     * @throws DivisionByZeroException If the divisor is zero.
550
     *
551
     * @pure
552
     */
553
    public function quotient(BigNumber|int|string $that): BigInteger
554
    {
555
        $that = BigInteger::of($that);
2,802✔
556

557
        if ($that->value === '1') {
2,802✔
558
            return $this;
1,470✔
559
        }
560

561
        if ($that->value === '0') {
1,923✔
562
            throw DivisionByZeroException::divisionByZero();
3✔
563
        }
564

565
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
1,920✔
566

567
        return new BigInteger($quotient);
1,920✔
568
    }
569

570
    /**
571
     * Returns the remainder of the division of this number by the given one.
572
     *
573
     * The remainder, when non-zero, has the same sign as the dividend.
574
     *
575
     * Examples:
576
     *
577
     * - `7` remainder `3` returns `1`
578
     * - `7` remainder `-3` returns `1`
579
     * - `-7` remainder `3` returns `-1`
580
     * - `-7` remainder `-3` returns `-1`
581
     *
582
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
583
     *
584
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
585
     * @throws DivisionByZeroException If the divisor is zero.
586
     *
587
     * @pure
588
     */
589
    public function remainder(BigNumber|int|string $that): BigInteger
590
    {
591
        $that = BigInteger::of($that);
273✔
592

593
        if ($that->value === '1') {
273✔
594
            return BigInteger::zero();
24✔
595
        }
596

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

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

603
        return new BigInteger($remainder);
246✔
604
    }
605

606
    /**
607
     * Returns the quotient and remainder of the division of this number by the given one.
608
     *
609
     * Examples:
610
     *
611
     * - `7` quotientAndRemainder `3` returns [`2`, `1`]
612
     * - `7` quotientAndRemainder `-3` returns [`-2`, `1`]
613
     * - `-7` quotientAndRemainder `3` returns [`-2`, `-1`]
614
     * - `-7` quotientAndRemainder `-3` returns [`2`, `-1`]
615
     *
616
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
617
     *
618
     * @return array{BigInteger, BigInteger} An array containing the quotient and the remainder.
619
     *
620
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
621
     * @throws DivisionByZeroException If the divisor is zero.
622
     *
623
     * @pure
624
     */
625
    public function quotientAndRemainder(BigNumber|int|string $that): array
626
    {
627
        $that = BigInteger::of($that);
147✔
628

629
        if ($that->value === '0') {
147✔
630
            throw DivisionByZeroException::divisionByZero();
3✔
631
        }
632

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

635
        return [
144✔
636
            new BigInteger($quotient),
144✔
637
            new BigInteger($remainder),
144✔
638
        ];
144✔
639
    }
640

641
    /**
642
     * Returns this number modulo the given one.
643
     *
644
     * The result is always non-negative, and is the unique value `r` such that `0 <= r < m`
645
     * and `this - r` is a multiple of `m`.
646
     *
647
     * This is also known as Euclidean modulo. Unlike `remainder()`, which can return negative values
648
     * when the dividend is negative, `mod()` always returns a non-negative result.
649
     *
650
     * Examples:
651
     *
652
     * - `7` mod `3` returns `1`
653
     * - `-7` mod `3` returns `2`
654
     *
655
     * @param BigNumber|int|string $modulus The modulus, strictly positive. Must be convertible to a BigInteger.
656
     *
657
     * @throws MathException           If the modulus is not valid, or is not convertible to a BigInteger.
658
     * @throws DivisionByZeroException If the modulus is zero.
659
     * @throws NegativeNumberException If the modulus is negative.
660
     *
661
     * @pure
662
     */
663
    public function mod(BigNumber|int|string $modulus): BigInteger
664
    {
665
        $modulus = BigInteger::of($modulus);
105✔
666

667
        if ($modulus->isZero()) {
105✔
668
            throw DivisionByZeroException::zeroModulus();
3✔
669
        }
670

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

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

677
        return new BigInteger($value);
99✔
678
    }
679

680
    /**
681
     * Returns the modular multiplicative inverse of this BigInteger modulo $modulus.
682
     *
683
     * @param BigNumber|int|string $modulus The modulus. Must be convertible to a BigInteger.
684
     *
685
     * @throws DivisionByZeroException If $modulus is zero.
686
     * @throws NegativeNumberException If $modulus is negative.
687
     * @throws MathException           If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger
688
     *                                 is not relatively prime to m).
689
     *
690
     * @pure
691
     */
692
    public function modInverse(BigNumber|int|string $modulus): BigInteger
693
    {
694
        $modulus = BigInteger::of($modulus);
75✔
695

696
        if ($modulus->isZero()) {
75✔
697
            throw DivisionByZeroException::zeroModulus();
6✔
698
        }
699

700
        if ($modulus->isNegative()) {
69✔
701
            throw NegativeNumberException::negativeModulus();
3✔
702
        }
703

704
        if ($modulus->value === '1') {
66✔
705
            return BigInteger::zero();
3✔
706
        }
707

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

710
        if ($value === null) {
63✔
711
            throw NoInverseException::noModularInverse();
15✔
712
        }
713

714
        return new BigInteger($value);
48✔
715
    }
716

717
    /**
718
     * Returns this number raised into power with modulo.
719
     *
720
     * This operation requires a non-negative exponent and a strictly positive modulus.
721
     *
722
     * @param BigNumber|int|string $exponent The exponent. Must be positive or zero.
723
     * @param BigNumber|int|string $modulus  The modulus. Must be strictly positive.
724
     *
725
     * @throws MathException           If the exponent or modulus is not valid, or not convertible to a BigInteger.
726
     * @throws NegativeNumberException If the exponent or modulus is negative.
727
     * @throws DivisionByZeroException If the modulus is zero.
728
     *
729
     * @pure
730
     */
731
    public function modPow(BigNumber|int|string $exponent, BigNumber|int|string $modulus): BigInteger
732
    {
733
        $exponent = BigInteger::of($exponent);
185✔
734
        $modulus = BigInteger::of($modulus);
185✔
735

736
        if ($exponent->isNegative()) {
185✔
737
            throw NegativeNumberException::negativeExponent();
3✔
738
        }
739

740
        if ($modulus->isZero()) {
182✔
741
            throw DivisionByZeroException::zeroModulus();
3✔
742
        }
743

744
        if ($modulus->isNegative()) {
179✔
745
            throw NegativeNumberException::negativeModulus();
3✔
746
        }
747

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

750
        return new BigInteger($result);
176✔
751
    }
752

753
    /**
754
     * Returns the greatest common divisor of this number and the given one.
755
     *
756
     * The GCD is always positive, unless both operands are 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 gcd(BigNumber|int|string $that): BigInteger
765
    {
766
        $that = BigInteger::of($that);
5,055✔
767

768
        if ($that->value === '0' && $this->value[0] !== '-') {
5,055✔
769
            return $this;
66✔
770
        }
771

772
        if ($this->value === '0' && $that->value[0] !== '-') {
4,989✔
773
            return $that;
300✔
774
        }
775

776
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
4,899✔
777

778
        return new BigInteger($value);
4,899✔
779
    }
780

781
    /**
782
     * Returns the least common multiple of this number and the given one.
783
     *
784
     * The LCM is always positive, unless at least one operand is zero, in which case it is zero.
785
     *
786
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
787
     *
788
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
789
     *
790
     * @pure
791
     */
792
    public function lcm(BigNumber|int|string $that): BigInteger
793
    {
794
        $that = BigInteger::of($that);
561✔
795

796
        if ($this->isZero() || $that->isZero()) {
561✔
797
            return BigInteger::zero();
99✔
798
        }
799

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

802
        return new BigInteger($value);
462✔
803
    }
804

805
    /**
806
     * Returns the integer square root of this number, rounded according to the given rounding mode.
807
     *
808
     * @param RoundingMode $roundingMode The rounding mode to use, defaults to Unnecessary.
809
     *
810
     * @throws NegativeNumberException    If this number is negative.
811
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and the number is not a perfect square.
812
     *
813
     * @pure
814
     */
815
    public function sqrt(RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
816
    {
817
        if ($this->value[0] === '-') {
10,623✔
818
            throw NegativeNumberException::squareRootOfNegativeNumber();
3✔
819
        }
820

821
        $calculator = CalculatorRegistry::get();
10,620✔
822

823
        $sqrt = $calculator->sqrt($this->value);
10,620✔
824

825
        // For Down and Floor (equivalent for non-negative numbers), return floor sqrt
826
        if ($roundingMode === RoundingMode::Down || $roundingMode === RoundingMode::Floor) {
10,620✔
827
            return new BigInteger($sqrt);
2,130✔
828
        }
829

830
        // Check if the sqrt is exact
831
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
832
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
833

834
        if ($remainder === '0') {
8,490✔
835
            // sqrt is exact
836
            return new BigInteger($sqrt);
5,385✔
837
        }
838

839
        // sqrt is not exact
840
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
841
            throw RoundingNecessaryException::roundingNecessary();
390✔
842
        }
843

844
        // For Up and Ceiling (equivalent for non-negative numbers), round up
845
        if ($roundingMode === RoundingMode::Up || $roundingMode === RoundingMode::Ceiling) {
2,715✔
846
            return new BigInteger($calculator->add($sqrt, '1'));
780✔
847
        }
848

849
        // For Half* modes, compare our number to the midpoint of the interval [s², (s+1)²[.
850
        // The midpoint is s² + s + 0.5. Comparing n >= s² + s + 0.5 with remainder = n − s²
851
        // is equivalent to comparing 2*remainder >= 2*s + 1.
852
        $twoRemainder = $calculator->mul($remainder, '2');
1,935✔
853
        $threshold = $calculator->add($calculator->mul($sqrt, '2'), '1');
1,935✔
854
        $cmp = $calculator->cmp($twoRemainder, $threshold);
1,935✔
855

856
        // We're supposed to increment (round up) when:
857
        //   - HalfUp, HalfCeiling => $cmp >= 0
858
        //   - HalfDown, HalfFloor => $cmp > 0
859
        //   - HalfEven => $cmp > 0 || ($cmp === 0 && $sqrt % 2 === 1)
860
        // But 2*remainder is always even and 2*s + 1 is always odd, so $cmp is never zero.
861
        // Therefore, all Half* modes simplify to:
862
        if ($cmp > 0) {
1,935✔
863
            $sqrt = $calculator->add($sqrt, '1');
990✔
864
        }
865

866
        return new BigInteger($sqrt);
1,935✔
867
    }
868

869
    #[Override]
870
    public function negated(): static
871
    {
872
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,798✔
873
    }
874

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

890
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
891
    }
892

893
    /**
894
     * Returns the integer bitwise-or combined with another integer.
895
     *
896
     * This method returns a negative BigInteger if and only if either of the operands is negative.
897
     *
898
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
899
     *
900
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
901
     *
902
     * @pure
903
     */
904
    public function or(BigNumber|int|string $that): BigInteger
905
    {
906
        $that = BigInteger::of($that);
138✔
907

908
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
909
    }
910

911
    /**
912
     * Returns the integer bitwise-xor combined with another integer.
913
     *
914
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
915
     *
916
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
917
     *
918
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
919
     *
920
     * @pure
921
     */
922
    public function xor(BigNumber|int|string $that): BigInteger
923
    {
924
        $that = BigInteger::of($that);
144✔
925

926
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
927
    }
928

929
    /**
930
     * Returns the bitwise-not of this BigInteger.
931
     *
932
     * @pure
933
     */
934
    public function not(): BigInteger
935
    {
936
        return $this->negated()->minus(1);
57✔
937
    }
938

939
    /**
940
     * Returns the integer left shifted by a given number of bits.
941
     *
942
     * @throws InvalidArgumentException If the number of bits is out of range.
943
     *
944
     * @pure
945
     */
946
    public function shiftedLeft(int $bits): BigInteger
947
    {
948
        if ($bits === 0) {
594✔
949
            return $this;
6✔
950
        }
951

952
        if ($bits < 0) {
588✔
953
            return $this->shiftedRight(-$bits);
198✔
954
        }
955

956
        return $this->multipliedBy(BigInteger::of(2)->power($bits));
390✔
957
    }
958

959
    /**
960
     * Returns the integer right shifted by a given number of bits.
961
     *
962
     * @throws InvalidArgumentException If the number of bits is out of range.
963
     *
964
     * @pure
965
     */
966
    public function shiftedRight(int $bits): BigInteger
967
    {
968
        if ($bits === 0) {
1,518✔
969
            return $this;
66✔
970
        }
971

972
        if ($bits < 0) {
1,452✔
973
            return $this->shiftedLeft(-$bits);
195✔
974
        }
975

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

978
        if ($this->isPositiveOrZero()) {
1,257✔
979
            return $this->quotient($operand);
672✔
980
        }
981

982
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
983
    }
984

985
    /**
986
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
987
     *
988
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
989
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
990
     *
991
     * @pure
992
     */
993
    public function getBitLength(): int
994
    {
995
        if ($this->value === '0') {
321✔
996
            return 0;
12✔
997
        }
998

999
        if ($this->isNegative()) {
315✔
1000
            return $this->abs()->minus(1)->getBitLength();
120✔
1001
        }
1002

1003
        return strlen($this->toBase(2));
309✔
1004
    }
1005

1006
    /**
1007
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
1008
     *
1009
     * Returns -1 if this BigInteger contains no one bits.
1010
     *
1011
     * @pure
1012
     */
1013
    public function getLowestSetBit(): int
1014
    {
1015
        $n = $this;
81✔
1016
        $bitLength = $this->getBitLength();
81✔
1017

1018
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
1019
            if ($n->isOdd()) {
81✔
1020
                return $i;
78✔
1021
            }
1022

1023
            $n = $n->shiftedRight(1);
51✔
1024
        }
1025

1026
        return -1;
3✔
1027
    }
1028

1029
    /**
1030
     * Returns whether this number is even.
1031
     *
1032
     * @pure
1033
     */
1034
    public function isEven(): bool
1035
    {
1036
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
1037
    }
1038

1039
    /**
1040
     * Returns whether this number is odd.
1041
     *
1042
     * @pure
1043
     */
1044
    public function isOdd(): bool
1045
    {
1046
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
1047
    }
1048

1049
    /**
1050
     * Returns true if and only if the designated bit is set.
1051
     *
1052
     * Computes ((this & (1<<n)) != 0).
1053
     *
1054
     * @param int $n The bit to test, 0-based.
1055
     *
1056
     * @throws InvalidArgumentException If the bit to test is negative.
1057
     *
1058
     * @pure
1059
     */
1060
    public function testBit(int $n): bool
1061
    {
1062
        if ($n < 0) {
873✔
1063
            throw InvalidArgumentException::negativeBitIndex();
3✔
1064
        }
1065

1066
        return $this->shiftedRight($n)->isOdd();
870✔
1067
    }
1068

1069
    #[Override]
1070
    public function compareTo(BigNumber|int|string $that): int
1071
    {
1072
        $that = BigNumber::of($that);
2,327✔
1073

1074
        if ($that instanceof BigInteger) {
2,327✔
1075
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,219✔
1076
        }
1077

1078
        return -$that->compareTo($this);
108✔
1079
    }
1080

1081
    #[Override]
1082
    public function getSign(): int
1083
    {
1084
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
5,894✔
1085
    }
1086

1087
    #[Override]
1088
    public function toBigInteger(): BigInteger
1089
    {
1090
        return $this;
24,602✔
1091
    }
1092

1093
    #[Override]
1094
    public function toBigDecimal(): BigDecimal
1095
    {
1096
        return self::newBigDecimal($this->value);
5,259✔
1097
    }
1098

1099
    #[Override]
1100
    public function toBigRational(): BigRational
1101
    {
1102
        return self::newBigRational($this, BigInteger::one(), false, false);
477✔
1103
    }
1104

1105
    #[Override]
1106
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1107
    {
1108
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1109
    }
1110

1111
    #[Override]
1112
    public function toInt(): int
1113
    {
1114
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1115

1116
        if ($intValue === false) {
87✔
1117
            throw IntegerOverflowException::integerOverflow($this);
15✔
1118
        }
1119

1120
        return $intValue;
72✔
1121
    }
1122

1123
    #[Override]
1124
    public function toFloat(): float
1125
    {
1126
        return (float) $this->value;
183✔
1127
    }
1128

1129
    /**
1130
     * Returns a string representation of this number in the given base.
1131
     *
1132
     * The output will always be lowercase for bases greater than 10.
1133
     *
1134
     * @throws InvalidArgumentException If the base is out of range.
1135
     *
1136
     * @pure
1137
     */
1138
    public function toBase(int $base): string
1139
    {
1140
        if ($base === 10) {
1,293✔
1141
            return $this->value;
12✔
1142
        }
1143

1144
        if ($base < 2 || $base > 36) {
1,281✔
1145
            throw InvalidArgumentException::baseOutOfRange($base);
15✔
1146
        }
1147

1148
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1149
    }
1150

1151
    /**
1152
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1153
     *
1154
     * This method is byte-oriented: the alphabet is interpreted as a sequence of single-byte characters.
1155
     * Multibyte UTF-8 characters are not supported.
1156
     *
1157
     * Because this method accepts any single-byte character, including dash, it does not handle negative numbers;
1158
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1159
     *
1160
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1161
     *
1162
     * @throws NegativeNumberException  If this number is negative.
1163
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
1164
     *
1165
     * @pure
1166
     */
1167
    public function toArbitraryBase(string $alphabet): string
1168
    {
1169
        $base = strlen($alphabet);
144✔
1170

1171
        if ($base < 2) {
144✔
1172
            throw InvalidArgumentException::alphabetTooShort();
6✔
1173
        }
1174

1175
        if (strlen(count_chars($alphabet, 3)) !== $base) {
138✔
1176
            throw InvalidArgumentException::duplicateCharsInAlphabet();
9✔
1177
        }
1178

1179
        if ($this->value[0] === '-') {
129✔
1180
            throw NegativeNumberException::notSupportedForNegativeNumber(__FUNCTION__);
3✔
1181
        }
1182

1183
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1184
    }
1185

1186
    /**
1187
     * Returns a string of bytes containing the binary representation of this BigInteger.
1188
     *
1189
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1190
     *
1191
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1192
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1193
     * number is negative.
1194
     *
1195
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1196
     * if `$signed` is true.
1197
     *
1198
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1199
     *
1200
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1201
     *
1202
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1203
     *
1204
     * @pure
1205
     */
1206
    public function toBytes(bool $signed = true): string
1207
    {
1208
        if (! $signed && $this->isNegative()) {
534✔
1209
            throw NegativeNumberException::unsignedBytesOfNegativeNumber();
3✔
1210
        }
1211

1212
        $hex = $this->abs()->toBase(16);
531✔
1213

1214
        if (strlen($hex) % 2 !== 0) {
531✔
1215
            $hex = '0' . $hex;
219✔
1216
        }
1217

1218
        $baseHexLength = strlen($hex);
531✔
1219

1220
        if ($signed) {
531✔
1221
            if ($this->isNegative()) {
492✔
1222
                $bin = hex2bin($hex);
453✔
1223
                assert($bin !== false);
1224

1225
                $hex = bin2hex(~$bin);
453✔
1226
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1227

1228
                $hexLength = strlen($hex);
453✔
1229

1230
                if ($hexLength < $baseHexLength) {
453✔
1231
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1232
                }
1233

1234
                if ($hex[0] < '8') {
453✔
1235
                    $hex = 'FF' . $hex;
114✔
1236
                }
1237
            } else {
1238
                if ($hex[0] >= '8') {
39✔
1239
                    $hex = '00' . $hex;
21✔
1240
                }
1241
            }
1242
        }
1243

1244
        $result = hex2bin($hex);
531✔
1245
        assert($result !== false);
1246

1247
        return $result;
531✔
1248
    }
1249

1250
    /**
1251
     * @return numeric-string
1252
     */
1253
    #[Override]
1254
    public function toString(): string
1255
    {
1256
        /** @var numeric-string */
1257
        return $this->value;
23,802✔
1258
    }
1259

1260
    /**
1261
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1262
     *
1263
     * @internal
1264
     *
1265
     * @return array{value: string}
1266
     */
1267
    public function __serialize(): array
1268
    {
1269
        return ['value' => $this->value];
6✔
1270
    }
1271

1272
    /**
1273
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1274
     *
1275
     * @internal
1276
     *
1277
     * @param array{value: string} $data
1278
     *
1279
     * @throws LogicException
1280
     */
1281
    public function __unserialize(array $data): void
1282
    {
1283
        /** @phpstan-ignore isset.initializedProperty */
1284
        if (isset($this->value)) {
9✔
1285
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1286
        }
1287

1288
        /** @phpstan-ignore deadCode.unreachable */
1289
        $this->value = $data['value'];
6✔
1290
    }
1291

1292
    #[Override]
1293
    protected static function from(BigNumber $number): static
1294
    {
1295
        return $number->toBigInteger();
24,740✔
1296
    }
1297
}
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