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

brick / math / 21788758024

07 Feb 2026 11:34PM UTC coverage: 98.544% (-0.8%) from 99.37%
21788758024

push

github

BenMorel
Add fast-path optimizations

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

14 existing lines in 4 files now uncovered.

1354 of 1374 relevant lines covered (98.54%)

2270.88 hits per line

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

98.43
/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\RandomSourceException;
15
use Brick\Math\Exception\RoundingNecessaryException;
16
use Brick\Math\Internal\CalculatorRegistry;
17
use Brick\Math\Internal\Constants;
18
use LogicException;
19
use Override;
20
use Throwable;
21

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

41
use const FILTER_VALIDATE_INT;
42

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

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

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

95
        if ($number === '') {
2,078✔
96
            throw NumberFormatException::emptyNumber();
3✔
97
        }
98

99
        $originalNumber = $number;
2,075✔
100

101
        if ($number[0] === '-') {
2,075✔
102
            $sign = '-';
27✔
103
            $number = substr($number, 1);
27✔
104
        } elseif ($number[0] === '+') {
2,048✔
105
            $sign = '';
27✔
106
            $number = substr($number, 1);
27✔
107
        } else {
108
            $sign = '';
2,021✔
109
        }
110

111
        if ($number === '') {
2,075✔
112
            throw NumberFormatException::invalidFormat($originalNumber);
6✔
113
        }
114

115
        $number = ltrim($number, '0');
2,069✔
116

117
        if ($number === '') {
2,069✔
118
            // The result will be the same in any base, avoid further calculation.
119
            return BigInteger::zero();
84✔
120
        }
121

122
        if ($number === '1') {
1,988✔
123
            // The result will be the same in any base, avoid further calculation.
124
            return new BigInteger($sign . '1');
75✔
125
        }
126

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

129
        if (preg_match($pattern, strtolower($number), $matches) === 1) {
1,916✔
130
            throw NumberFormatException::charNotValidInBase($matches[0], $base);
111✔
131
        }
132

133
        if ($base === 10) {
1,805✔
134
            // The number is usable as is, avoid further calculation.
135
            return new BigInteger($sign . $number);
24✔
136
        }
137

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

140
        return new BigInteger($sign . $result);
1,781✔
141
    }
142

143
    /**
144
     * Parses a string containing an integer in an arbitrary base, using a custom alphabet.
145
     *
146
     * This method is byte-oriented: the alphabet is interpreted as a sequence of single-byte characters.
147
     * Multibyte UTF-8 characters are not supported.
148
     *
149
     * Because this method accepts any single-byte character, including dash, it does not handle negative numbers.
150
     *
151
     * @param string $number   The number to parse.
152
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
153
     *
154
     * @throws NumberFormatException    If the given number is empty or contains invalid chars for the given alphabet.
155
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
156
     *
157
     * @pure
158
     */
159
    public static function fromArbitraryBase(string $number, string $alphabet): BigInteger
160
    {
161
        $base = strlen($alphabet);
423✔
162

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

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

171
        if ($number === '') {
408✔
172
            throw NumberFormatException::emptyNumber();
3✔
173
        }
174

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

177
        if (preg_match($pattern, $number, $matches) === 1) {
405✔
178
            throw NumberFormatException::charNotInAlphabet($matches[0]);
27✔
179
        }
180

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

183
        return new BigInteger($number);
378✔
184
    }
185

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

211
        $twosComplement = false;
1,221✔
212

213
        if ($signed) {
1,221✔
214
            $x = ord($value[0]);
984✔
215

216
            if (($twosComplement = ($x >= 0x80))) {
984✔
217
                $value = ~$value;
906✔
218
            }
219
        }
220

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

223
        if ($twosComplement) {
1,221✔
224
            return $number->plus(1)->negated();
906✔
225
        }
226

227
        return $number;
315✔
228
    }
229

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

249
        if ($numBits === 0) {
177✔
250
            return BigInteger::zero();
3✔
251
        }
252

253
        /** @var int<1, max> $byteLength */
254
        $byteLength = intdiv($numBits - 1, 8) + 1;
174✔
255

256
        $extraBits = ($byteLength * 8 - $numBits);
174✔
257
        $bitmask = chr(0xFF >> $extraBits);
174✔
258

259
        $randomBytes = self::randomBytes($byteLength, $randomBytesGenerator);
174✔
260
        $randomBytes[0] = $randomBytes[0] & $bitmask;
159✔
261

262
        return self::fromBytes($randomBytes, false);
159✔
263
    }
264

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

288
        if ($min->isGreaterThan($max)) {
90✔
289
            throw InvalidArgumentException::minGreaterThanMax();
3✔
290
        }
291

292
        if ($min->isEqualTo($max)) {
87✔
293
            return $min;
3✔
294
        }
295

296
        $diff = $max->minus($min);
84✔
297
        $bitLength = $diff->getBitLength();
84✔
298

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

304
        return $randomNumber->plus($min);
78✔
305
    }
306

307
    /**
308
     * Returns a BigInteger representing zero.
309
     *
310
     * @pure
311
     */
312
    public static function zero(): BigInteger
313
    {
314
        /** @var BigInteger|null $zero */
315
        static $zero;
231✔
316

317
        if ($zero === null) {
231✔
UNCOV
318
            $zero = new BigInteger('0');
×
319
        }
320

321
        return $zero;
231✔
322
    }
323

324
    /**
325
     * Returns a BigInteger representing one.
326
     *
327
     * @pure
328
     */
329
    public static function one(): BigInteger
330
    {
331
        /** @var BigInteger|null $one */
332
        static $one;
702✔
333

334
        if ($one === null) {
702✔
UNCOV
335
            $one = new BigInteger('1');
×
336
        }
337

338
        return $one;
702✔
339
    }
340

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

351
        if ($ten === null) {
6✔
352
            $ten = new BigInteger('10');
3✔
353
        }
354

355
        return $ten;
6✔
356
    }
357

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

374
        foreach ($n as $next) {
1,587✔
375
            $result = $result->gcd(BigInteger::of($next));
1,560✔
376

377
            if ($result->isEqualTo(1)) {
1,560✔
378
                return $result;
345✔
379
            }
380
        }
381

382
        return $result;
1,242✔
383
    }
384

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

401
        foreach ($n as $next) {
324✔
402
            $result = $result->lcm(BigInteger::of($next));
297✔
403

404
            if ($result->isZero()) {
297✔
405
                return $result;
51✔
406
            }
407
        }
408

409
        return $result;
273✔
410
    }
411

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

425
        if ($that->value === '0') {
1,629✔
426
            return $this;
30✔
427
        }
428

429
        if ($this->value === '0') {
1,599✔
430
            return $that;
72✔
431
        }
432

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

435
        return new BigInteger($value);
1,548✔
436
    }
437

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

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

455
        $value = CalculatorRegistry::get()->sub($this->value, $that->value);
1,086✔
456

457
        return new BigInteger($value);
1,086✔
458
    }
459

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

473
        if ($that->value === '1') {
1,500✔
474
            return $this;
582✔
475
        }
476

477
        if ($this->value === '1') {
1,323✔
478
            return $that;
426✔
479
        }
480

481
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
1,200✔
482

483
        return new BigInteger($value);
1,200✔
484
    }
485

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

502
        if ($that->value === '1') {
1,968✔
503
            return $this;
3✔
504
        }
505

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

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

512
        if ($result === null) {
1,959✔
513
            throw RoundingNecessaryException::integerDivisionNotExact();
117✔
514
        }
515

516
        return new BigInteger($result);
1,866✔
517
    }
518

519
    /**
520
     * Returns this number exponentiated to the given value.
521
     *
522
     * @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
523
     *
524
     * @pure
525
     */
526
    public function power(int $exponent): BigInteger
527
    {
528
        if ($exponent === 0) {
1,875✔
529
            return BigInteger::one();
27✔
530
        }
531

532
        if ($exponent === 1) {
1,848✔
533
            return $this;
204✔
534
        }
535

536
        if ($exponent < 0 || $exponent > Constants::MAX_POWER) {
1,644✔
537
            throw InvalidArgumentException::exponentOutOfRange($exponent, 0, Constants::MAX_POWER);
6✔
538
        }
539

540
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,638✔
541
    }
542

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

564
        if ($that->value === '1') {
3,036✔
565
            return $this;
1,695✔
566
        }
567

568
        if ($that->value === '-1') {
2,091✔
569
            return $this->negated();
9✔
570
        }
571

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

576
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
2,079✔
577

578
        return new BigInteger($quotient);
2,079✔
579
    }
580

581
    /**
582
     * Returns the remainder of the division of this number by the given one.
583
     *
584
     * The remainder, when non-zero, has the same sign as the dividend.
585
     *
586
     * Examples:
587
     *
588
     * - `7` remainder `3` returns `1`
589
     * - `7` remainder `-3` returns `1`
590
     * - `-7` remainder `3` returns `-1`
591
     * - `-7` remainder `-3` returns `-1`
592
     *
593
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
594
     *
595
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
596
     * @throws DivisionByZeroException If the divisor is zero.
597
     *
598
     * @pure
599
     */
600
    public function remainder(BigNumber|int|string $that): BigInteger
601
    {
602
        $that = BigInteger::of($that);
273✔
603

604
        if ($that->value === '1' || $that->value === '-1') {
273✔
605
            return BigInteger::zero();
33✔
606
        }
607

608
        if ($that->value === '0') {
240✔
609
            throw DivisionByZeroException::divisionByZero();
3✔
610
        }
611

612
        $remainder = CalculatorRegistry::get()->divR($this->value, $that->value);
237✔
613

614
        return new BigInteger($remainder);
237✔
615
    }
616

617
    /**
618
     * Returns the quotient and remainder of the division of this number by the given one.
619
     *
620
     * Examples:
621
     *
622
     * - `7` quotientAndRemainder `3` returns [`2`, `1`]
623
     * - `7` quotientAndRemainder `-3` returns [`-2`, `1`]
624
     * - `-7` quotientAndRemainder `3` returns [`-2`, `-1`]
625
     * - `-7` quotientAndRemainder `-3` returns [`2`, `-1`]
626
     *
627
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
628
     *
629
     * @return array{BigInteger, BigInteger} An array containing the quotient and the remainder.
630
     *
631
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
632
     * @throws DivisionByZeroException If the divisor is zero.
633
     *
634
     * @pure
635
     */
636
    public function quotientAndRemainder(BigNumber|int|string $that): array
637
    {
638
        $that = BigInteger::of($that);
147✔
639

640
        if ($that->value === '0') {
147✔
641
            throw DivisionByZeroException::divisionByZero();
3✔
642
        }
643

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

646
        return [
144✔
647
            new BigInteger($quotient),
144✔
648
            new BigInteger($remainder),
144✔
649
        ];
144✔
650
    }
651

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

678
        if ($modulus->isZero()) {
105✔
679
            throw DivisionByZeroException::zeroModulus();
3✔
680
        }
681

682
        if ($modulus->isNegative()) {
102✔
683
            throw InvalidArgumentException::negativeModulus();
3✔
684
        }
685

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

688
        return new BigInteger($value);
99✔
689
    }
690

691
    /**
692
     * Returns the modular multiplicative inverse of this BigInteger modulo $modulus.
693
     *
694
     * @param BigNumber|int|string $modulus The modulus. Must be convertible to a BigInteger.
695
     *
696
     * @throws MathException            If the modulus is not valid, or is not convertible to a BigInteger.
697
     * @throws DivisionByZeroException  If $modulus is zero.
698
     * @throws InvalidArgumentException If $modulus is negative.
699
     * @throws NoInverseException       If this BigInteger has no multiplicative inverse mod m (that is, this BigInteger
700
     *                                  is not relatively prime to m).
701
     *
702
     * @pure
703
     */
704
    public function modInverse(BigNumber|int|string $modulus): BigInteger
705
    {
706
        $modulus = BigInteger::of($modulus);
75✔
707

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

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

716
        if ($modulus->value === '1') {
66✔
717
            return BigInteger::zero();
3✔
718
        }
719

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

722
        if ($value === null) {
63✔
723
            throw NoInverseException::noModularInverse();
15✔
724
        }
725

726
        return new BigInteger($value);
48✔
727
    }
728

729
    /**
730
     * Returns this number raised into power with modulo.
731
     *
732
     * This operation requires a non-negative exponent and a strictly positive modulus.
733
     *
734
     * @param BigNumber|int|string $exponent The exponent. Must be positive or zero.
735
     * @param BigNumber|int|string $modulus  The modulus. Must be strictly positive.
736
     *
737
     * @throws MathException            If the exponent or modulus is not valid, or not convertible to a BigInteger.
738
     * @throws InvalidArgumentException If the exponent or modulus is negative.
739
     * @throws DivisionByZeroException  If the modulus is zero.
740
     *
741
     * @pure
742
     */
743
    public function modPow(BigNumber|int|string $exponent, BigNumber|int|string $modulus): BigInteger
744
    {
745
        $exponent = BigInteger::of($exponent);
185✔
746
        $modulus = BigInteger::of($modulus);
185✔
747

748
        if ($modulus->isZero()) {
185✔
749
            throw DivisionByZeroException::zeroModulus();
3✔
750
        }
751

752
        if ($modulus->isNegative()) {
182✔
753
            throw InvalidArgumentException::negativeModulus();
3✔
754
        }
755

756
        if ($exponent->isNegative()) {
179✔
757
            throw InvalidArgumentException::negativeExponent();
3✔
758
        }
759

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

762
        return new BigInteger($result);
176✔
763
    }
764

765
    /**
766
     * Returns the greatest common divisor of this number and the given one.
767
     *
768
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
769
     *
770
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
771
     *
772
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
773
     *
774
     * @pure
775
     */
776
    public function gcd(BigNumber|int|string $that): BigInteger
777
    {
778
        $that = BigInteger::of($that);
5,289✔
779

780
        if ($that->value === '0' && $this->value[0] !== '-') {
5,289✔
781
            return $this;
66✔
782
        }
783

784
        if ($this->value === '0' && $that->value[0] !== '-') {
5,223✔
785
            return $that;
417✔
786
        }
787

788
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
5,106✔
789

790
        return new BigInteger($value);
5,106✔
791
    }
792

793
    /**
794
     * Returns the least common multiple of this number and the given one.
795
     *
796
     * The LCM is always positive, unless at least one operand is zero, in which case it is zero.
797
     *
798
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
799
     *
800
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
801
     *
802
     * @pure
803
     */
804
    public function lcm(BigNumber|int|string $that): BigInteger
805
    {
806
        $that = BigInteger::of($that);
561✔
807

808
        if ($this->isZero() || $that->isZero()) {
561✔
809
            return BigInteger::zero();
99✔
810
        }
811

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

814
        return new BigInteger($value);
462✔
815
    }
816

817
    /**
818
     * Returns the integer square root of this number, rounded according to the given rounding mode.
819
     *
820
     * @param RoundingMode $roundingMode An optional rounding mode, defaults to Unnecessary.
821
     *
822
     * @throws NegativeNumberException    If this number is negative.
823
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and the number is not a perfect square.
824
     *
825
     * @pure
826
     */
827
    public function sqrt(RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
828
    {
829
        if ($this->value[0] === '-') {
10,623✔
830
            throw NegativeNumberException::squareRootOfNegativeNumber();
3✔
831
        }
832

833
        $calculator = CalculatorRegistry::get();
10,620✔
834

835
        $sqrt = $calculator->sqrt($this->value);
10,620✔
836

837
        // For Down and Floor (equivalent for non-negative numbers), return floor sqrt
838
        if ($roundingMode === RoundingMode::Down || $roundingMode === RoundingMode::Floor) {
10,620✔
839
            return new BigInteger($sqrt);
2,130✔
840
        }
841

842
        // Check if the sqrt is exact
843
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
844
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
845

846
        if ($remainder === '0') {
8,490✔
847
            // sqrt is exact
848
            return new BigInteger($sqrt);
5,385✔
849
        }
850

851
        // sqrt is not exact
852
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
853
            throw RoundingNecessaryException::integerSquareRootNotExact();
390✔
854
        }
855

856
        // For Up and Ceiling (equivalent for non-negative numbers), round up
857
        if ($roundingMode === RoundingMode::Up || $roundingMode === RoundingMode::Ceiling) {
2,715✔
858
            return new BigInteger($calculator->add($sqrt, '1'));
780✔
859
        }
860

861
        // For Half* modes, compare our number to the midpoint of the interval [s², (s+1)²[.
862
        // The midpoint is s² + s + 0.5. Comparing n >= s² + s + 0.5 with remainder = n − s²
863
        // is equivalent to comparing 2*remainder >= 2*s + 1.
864
        $twoRemainder = $calculator->mul($remainder, '2');
1,935✔
865
        $threshold = $calculator->add($calculator->mul($sqrt, '2'), '1');
1,935✔
866
        $cmp = $calculator->cmp($twoRemainder, $threshold);
1,935✔
867

868
        // We're supposed to increment (round up) when:
869
        //   - HalfUp, HalfCeiling => $cmp >= 0
870
        //   - HalfDown, HalfFloor => $cmp > 0
871
        //   - HalfEven => $cmp > 0 || ($cmp === 0 && $sqrt % 2 === 1)
872
        // But 2*remainder is always even and 2*s + 1 is always odd, so $cmp is never zero.
873
        // Therefore, all Half* modes simplify to:
874
        if ($cmp > 0) {
1,935✔
875
            $sqrt = $calculator->add($sqrt, '1');
990✔
876
        }
877

878
        return new BigInteger($sqrt);
1,935✔
879
    }
880

881
    #[Override]
882
    public function negated(): static
883
    {
884
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,825✔
885
    }
886

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

902
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
903
    }
904

905
    /**
906
     * Returns the integer bitwise-or combined with another integer.
907
     *
908
     * This method returns a negative BigInteger if and only if either of the operands is negative.
909
     *
910
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
911
     *
912
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
913
     *
914
     * @pure
915
     */
916
    public function or(BigNumber|int|string $that): BigInteger
917
    {
918
        $that = BigInteger::of($that);
138✔
919

920
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
921
    }
922

923
    /**
924
     * Returns the integer bitwise-xor combined with another integer.
925
     *
926
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
927
     *
928
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
929
     *
930
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
931
     *
932
     * @pure
933
     */
934
    public function xor(BigNumber|int|string $that): BigInteger
935
    {
936
        $that = BigInteger::of($that);
144✔
937

938
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
939
    }
940

941
    /**
942
     * Returns the bitwise-not of this BigInteger.
943
     *
944
     * @pure
945
     */
946
    public function not(): BigInteger
947
    {
948
        return $this->negated()->minus(1);
57✔
949
    }
950

951
    /**
952
     * Returns the integer left shifted by a given number of bits.
953
     *
954
     * @throws InvalidArgumentException If the number of bits is not in the range -1,000,000 to 1,000,000.
955
     *
956
     * @pure
957
     */
958
    public function shiftedLeft(int $bits): BigInteger
959
    {
960
        if ($bits === 0) {
594✔
961
            return $this;
6✔
962
        }
963

964
        if ($bits > Constants::MAX_BIT_SHIFT || $bits < -Constants::MAX_BIT_SHIFT) {
588✔
UNCOV
965
            throw InvalidArgumentException::bitShiftOutOfRange($bits);
×
966
        }
967

968
        if ($bits < 0) {
588✔
969
            return $this->shiftedRight(-$bits);
198✔
970
        }
971

972
        return $this->multipliedBy(BigInteger::of(2)->power($bits));
390✔
973
    }
974

975
    /**
976
     * Returns the integer right shifted by a given number of bits.
977
     *
978
     * @throws InvalidArgumentException If the number of bits is not in the range -1,000,000 to 1,000,000.
979
     *
980
     * @pure
981
     */
982
    public function shiftedRight(int $bits): BigInteger
983
    {
984
        if ($bits === 0) {
1,518✔
985
            return $this;
66✔
986
        }
987

988
        if ($bits > Constants::MAX_BIT_SHIFT || $bits < -Constants::MAX_BIT_SHIFT) {
1,452✔
UNCOV
989
            throw InvalidArgumentException::bitShiftOutOfRange($bits);
×
990
        }
991

992
        if ($bits < 0) {
1,452✔
993
            return $this->shiftedLeft(-$bits);
195✔
994
        }
995

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

998
        if ($this->isPositiveOrZero()) {
1,257✔
999
            return $this->quotient($operand);
672✔
1000
        }
1001

1002
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
1003
    }
1004

1005
    /**
1006
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
1007
     *
1008
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
1009
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
1010
     *
1011
     * @pure
1012
     */
1013
    public function getBitLength(): int
1014
    {
1015
        if ($this->value === '0') {
327✔
1016
            return 0;
12✔
1017
        }
1018

1019
        if ($this->isNegative()) {
321✔
1020
            return $this->abs()->minus(1)->getBitLength();
120✔
1021
        }
1022

1023
        return strlen($this->toBase(2));
315✔
1024
    }
1025

1026
    /**
1027
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
1028
     *
1029
     * Returns -1 if this BigInteger contains no one bits.
1030
     *
1031
     * @pure
1032
     */
1033
    public function getLowestSetBit(): int
1034
    {
1035
        $n = $this;
81✔
1036
        $bitLength = $this->getBitLength();
81✔
1037

1038
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
1039
            if ($n->isOdd()) {
81✔
1040
                return $i;
78✔
1041
            }
1042

1043
            $n = $n->shiftedRight(1);
51✔
1044
        }
1045

1046
        return -1;
3✔
1047
    }
1048

1049
    /**
1050
     * Returns whether this number is even.
1051
     *
1052
     * @pure
1053
     */
1054
    public function isEven(): bool
1055
    {
1056
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
1057
    }
1058

1059
    /**
1060
     * Returns whether this number is odd.
1061
     *
1062
     * @pure
1063
     */
1064
    public function isOdd(): bool
1065
    {
1066
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
1067
    }
1068

1069
    /**
1070
     * Returns true if and only if the designated bit is set.
1071
     *
1072
     * Computes ((this & (1<<n)) != 0).
1073
     *
1074
     * @param int $n The bit to test, 0-based.
1075
     *
1076
     * @throws InvalidArgumentException If the bit to test is negative.
1077
     *
1078
     * @pure
1079
     */
1080
    public function testBit(int $n): bool
1081
    {
1082
        if ($n < 0) {
873✔
1083
            throw InvalidArgumentException::negativeBitIndex();
3✔
1084
        }
1085

1086
        return $this->shiftedRight($n)->isOdd();
870✔
1087
    }
1088

1089
    #[Override]
1090
    public function compareTo(BigNumber|int|string $that): int
1091
    {
1092
        $that = BigNumber::of($that);
2,384✔
1093

1094
        if ($that instanceof BigInteger) {
2,384✔
1095
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,264✔
1096
        }
1097

1098
        return -$that->compareTo($this);
120✔
1099
    }
1100

1101
    #[Override]
1102
    public function getSign(): int
1103
    {
1104
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
6,116✔
1105
    }
1106

1107
    #[Override]
1108
    public function toBigInteger(): BigInteger
1109
    {
1110
        return $this;
24,806✔
1111
    }
1112

1113
    #[Override]
1114
    public function toBigDecimal(): BigDecimal
1115
    {
1116
        return self::newBigDecimal($this->value);
4,995✔
1117
    }
1118

1119
    #[Override]
1120
    public function toBigRational(): BigRational
1121
    {
1122
        return self::newBigRational($this, BigInteger::one(), false, false);
660✔
1123
    }
1124

1125
    #[Override]
1126
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1127
    {
1128
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1129
    }
1130

1131
    #[Override]
1132
    public function toInt(): int
1133
    {
1134
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1135

1136
        if ($intValue === false) {
87✔
1137
            throw IntegerOverflowException::integerOutOfRange($this);
15✔
1138
        }
1139

1140
        return $intValue;
72✔
1141
    }
1142

1143
    #[Override]
1144
    public function toFloat(): float
1145
    {
1146
        return (float) $this->value;
183✔
1147
    }
1148

1149
    /**
1150
     * Returns a string representation of this number in the given base.
1151
     *
1152
     * The output will always be lowercase for bases greater than 10.
1153
     *
1154
     * @throws InvalidArgumentException If the base is out of range.
1155
     *
1156
     * @pure
1157
     */
1158
    public function toBase(int $base): string
1159
    {
1160
        if ($base === 10) {
1,299✔
1161
            return $this->value;
12✔
1162
        }
1163

1164
        if ($base < 2 || $base > 36) {
1,287✔
1165
            throw InvalidArgumentException::baseOutOfRange($base);
15✔
1166
        }
1167

1168
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,272✔
1169
    }
1170

1171
    /**
1172
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1173
     *
1174
     * This method is byte-oriented: the alphabet is interpreted as a sequence of single-byte characters.
1175
     * Multibyte UTF-8 characters are not supported.
1176
     *
1177
     * Because this method accepts any single-byte character, including dash, it does not handle negative numbers;
1178
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1179
     *
1180
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1181
     *
1182
     * @throws NegativeNumberException  If this number is negative.
1183
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars, or contains duplicates.
1184
     *
1185
     * @pure
1186
     */
1187
    public function toArbitraryBase(string $alphabet): string
1188
    {
1189
        $base = strlen($alphabet);
144✔
1190

1191
        if ($base < 2) {
144✔
1192
            throw InvalidArgumentException::alphabetTooShort();
6✔
1193
        }
1194

1195
        if (strlen(count_chars($alphabet, 3)) !== $base) {
138✔
1196
            throw InvalidArgumentException::duplicateCharsInAlphabet();
9✔
1197
        }
1198

1199
        if ($this->value[0] === '-') {
129✔
1200
            throw NegativeNumberException::toArbitraryBaseOfNegativeNumber();
3✔
1201
        }
1202

1203
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1204
    }
1205

1206
    /**
1207
     * Returns a string of bytes containing the binary representation of this BigInteger.
1208
     *
1209
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1210
     *
1211
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1212
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1213
     * number is negative.
1214
     *
1215
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1216
     * if `$signed` is true.
1217
     *
1218
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1219
     *
1220
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1221
     *
1222
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1223
     *
1224
     * @pure
1225
     */
1226
    public function toBytes(bool $signed = true): string
1227
    {
1228
        if (! $signed && $this->isNegative()) {
534✔
1229
            throw NegativeNumberException::unsignedBytesOfNegativeNumber();
3✔
1230
        }
1231

1232
        $hex = $this->abs()->toBase(16);
531✔
1233

1234
        if (strlen($hex) % 2 !== 0) {
531✔
1235
            $hex = '0' . $hex;
219✔
1236
        }
1237

1238
        $baseHexLength = strlen($hex);
531✔
1239

1240
        if ($signed) {
531✔
1241
            if ($this->isNegative()) {
492✔
1242
                $bin = hex2bin($hex);
453✔
1243
                assert($bin !== false);
1244

1245
                $hex = bin2hex(~$bin);
453✔
1246
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1247

1248
                $hexLength = strlen($hex);
453✔
1249

1250
                if ($hexLength < $baseHexLength) {
453✔
1251
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1252
                }
1253

1254
                if ($hex[0] < '8') {
453✔
1255
                    $hex = 'FF' . $hex;
114✔
1256
                }
1257
            } else {
1258
                if ($hex[0] >= '8') {
39✔
1259
                    $hex = '00' . $hex;
21✔
1260
                }
1261
            }
1262
        }
1263

1264
        $result = hex2bin($hex);
531✔
1265
        assert($result !== false);
1266

1267
        return $result;
531✔
1268
    }
1269

1270
    /**
1271
     * @return numeric-string
1272
     */
1273
    #[Override]
1274
    public function toString(): string
1275
    {
1276
        /** @var numeric-string */
1277
        return $this->value;
24,420✔
1278
    }
1279

1280
    /**
1281
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1282
     *
1283
     * @internal
1284
     *
1285
     * @return array{value: string}
1286
     */
1287
    public function __serialize(): array
1288
    {
1289
        return ['value' => $this->value];
6✔
1290
    }
1291

1292
    /**
1293
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1294
     *
1295
     * @internal
1296
     *
1297
     * @param array{value: string} $data
1298
     *
1299
     * @throws LogicException
1300
     */
1301
    public function __unserialize(array $data): void
1302
    {
1303
        /** @phpstan-ignore isset.initializedProperty */
1304
        if (isset($this->value)) {
9✔
1305
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1306
        }
1307

1308
        /** @phpstan-ignore deadCode.unreachable */
1309
        $this->value = $data['value'];
6✔
1310
    }
1311

1312
    #[Override]
1313
    protected static function from(BigNumber $number): static
1314
    {
1315
        return $number->toBigInteger();
24,908✔
1316
    }
1317

1318
    /**
1319
     * Returns random bytes from the provided generator or from random_bytes().
1320
     *
1321
     * @param int                          $byteLength           The number of requested bytes.
1322
     * @param (callable(int): string)|null $randomBytesGenerator The random bytes generator, or null to use random_bytes().
1323
     *
1324
     * @throws RandomSourceException If random byte generation fails.
1325
     */
1326
    private static function randomBytes(int $byteLength, ?callable $randomBytesGenerator): string
1327
    {
1328
        if ($randomBytesGenerator === null) {
174✔
UNCOV
1329
            $randomBytesGenerator = random_bytes(...);
×
1330
        }
1331

1332
        try {
1333
            $randomBytes = $randomBytesGenerator($byteLength);
174✔
1334
        } catch (Throwable $e) {
6✔
1335
            throw RandomSourceException::randomSourceFailure($e);
6✔
1336
        }
1337

1338
        /** @phpstan-ignore function.alreadyNarrowedType (Defensive runtime check for user-provided callbacks) */
1339
        if (! is_string($randomBytes)) {
168✔
1340
            throw RandomSourceException::invalidRandomBytesType($randomBytes);
6✔
1341
        }
1342

1343
        if (strlen($randomBytes) !== $byteLength) {
162✔
1344
            throw RandomSourceException::invalidRandomBytesLength($byteLength, strlen($randomBytes));
3✔
1345
        }
1346

1347
        return $randomBytes;
159✔
1348
    }
1349
}
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