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

brick / math / 21870644451

10 Feb 2026 03:15PM UTC coverage: 98.913% (-0.3%) from 99.188%
21870644451

push

github

BenMorel
Harmonize docs

1365 of 1380 relevant lines covered (98.91%)

2313.75 hits per line

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

99.07
/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\Calculator;
17
use Brick\Math\Internal\CalculatorRegistry;
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,448✔
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(Calculator::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✔
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;
714✔
333

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

338
        return $one;
714✔
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 additional numbers. Each number must be convertible to a 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 additional numbers. Each number must be convertible to a 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,611✔
424

425
        if ($that->isZero()) {
1,611✔
426
            return $this;
21✔
427
        }
428

429
        if ($this->isZero()) {
1,590✔
430
            return $that;
57✔
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);
303✔
450

451
        if ($that->isZero()) {
303✔
452
            return $this;
24✔
453
        }
454

455
        if ($this->isZero()) {
279✔
456
            return $that->negated();
9✔
457
        }
458

459
        $value = CalculatorRegistry::get()->sub($this->value, $that->value);
270✔
460

461
        return new BigInteger($value);
270✔
462
    }
463

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

477
        if ($that->isOne()) {
1,206✔
478
            return $this;
411✔
479
        }
480

481
        if ($this->isOne()) {
1,191✔
482
            return $that;
264✔
483
        }
484

485
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
1,056✔
486

487
        return new BigInteger($value);
1,056✔
488
    }
489

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

506
        if ($that->isZero()) {
1,968✔
507
            throw DivisionByZeroException::divisionByZero();
6✔
508
        }
509

510
        if ($that->isOne()) {
1,962✔
511
            return $this;
3✔
512
        }
513

514
        if ($that->isMinusOne()) {
1,959✔
515
            return $this->negated();
6✔
516
        }
517

518
        $result = CalculatorRegistry::get()->divRound($this->value, $that->value, $roundingMode);
1,953✔
519

520
        if ($result === null) {
1,953✔
521
            throw RoundingNecessaryException::integerDivisionNotExact();
117✔
522
        }
523

524
        return new BigInteger($result);
1,860✔
525
    }
526

527
    /**
528
     * Returns this number exponentiated to the given value.
529
     *
530
     * @throws InvalidArgumentException If the exponent is negative.
531
     *
532
     * @pure
533
     */
534
    public function power(int $exponent): BigInteger
535
    {
536
        if ($exponent === 0) {
1,875✔
537
            return BigInteger::one();
27✔
538
        }
539

540
        if ($exponent === 1) {
1,848✔
541
            return $this;
204✔
542
        }
543

544
        if ($exponent < 0) {
1,644✔
545
            throw InvalidArgumentException::negativeExponent();
3✔
546
        }
547

548
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,641✔
549
    }
550

551
    /**
552
     * Returns the quotient of the division of this number by the given one.
553
     *
554
     * Examples:
555
     *
556
     * - `7` quotient `3` returns `2`
557
     * - `7` quotient `-3` returns `-2`
558
     * - `-7` quotient `3` returns `-2`
559
     * - `-7` quotient `-3` returns `2`
560
     *
561
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
562
     *
563
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
564
     * @throws DivisionByZeroException If the divisor is zero.
565
     *
566
     * @pure
567
     */
568
    public function quotient(BigNumber|int|string $that): BigInteger
569
    {
570
        $that = BigInteger::of($that);
3,060✔
571

572
        if ($that->isZero()) {
3,060✔
573
            throw DivisionByZeroException::divisionByZero();
3✔
574
        }
575

576
        if ($that->isOne()) {
3,057✔
577
            return $this;
1,635✔
578
        }
579

580
        if ($that->isMinusOne()) {
1,905✔
581
            return $this->negated();
9✔
582
        }
583

584
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
1,896✔
585

586
        return new BigInteger($quotient);
1,896✔
587
    }
588

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

612
        if ($that->isZero()) {
273✔
613
            throw DivisionByZeroException::divisionByZero();
3✔
614
        }
615

616
        if ($that->isOne() || $that->isMinusOne()) {
270✔
617
            return BigInteger::zero();
33✔
618
        }
619

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

622
        return new BigInteger($remainder);
237✔
623
    }
624

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

648
        if ($that->isZero()) {
147✔
649
            throw DivisionByZeroException::divisionByZero();
3✔
650
        }
651

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

654
        return [
144✔
655
            new BigInteger($quotient),
144✔
656
            new BigInteger($remainder),
144✔
657
        ];
144✔
658
    }
659

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

686
        if ($modulus->isZero()) {
105✔
687
            throw DivisionByZeroException::zeroModulus();
3✔
688
        }
689

690
        if ($modulus->isNegative()) {
102✔
691
            throw InvalidArgumentException::negativeModulus();
3✔
692
        }
693

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

696
        return new BigInteger($value);
99✔
697
    }
698

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

716
        if ($modulus->isZero()) {
75✔
717
            throw DivisionByZeroException::zeroModulus();
6✔
718
        }
719

720
        if ($modulus->isNegative()) {
69✔
721
            throw InvalidArgumentException::negativeModulus();
3✔
722
        }
723

724
        if ($modulus->isOne()) {
66✔
725
            return BigInteger::zero();
3✔
726
        }
727

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

730
        if ($value === null) {
63✔
731
            throw NoInverseException::noModularInverse();
15✔
732
        }
733

734
        return new BigInteger($value);
48✔
735
    }
736

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

756
        if ($modulus->isZero()) {
185✔
757
            throw DivisionByZeroException::zeroModulus();
3✔
758
        }
759

760
        if ($modulus->isNegative()) {
182✔
761
            throw InvalidArgumentException::negativeModulus();
3✔
762
        }
763

764
        if ($exponent->isNegative()) {
179✔
765
            throw InvalidArgumentException::negativeExponent();
3✔
766
        }
767

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

770
        return new BigInteger($result);
176✔
771
    }
772

773
    /**
774
     * Returns the greatest common divisor of this number and the given one.
775
     *
776
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
777
     *
778
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
779
     *
780
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
781
     *
782
     * @pure
783
     */
784
    public function gcd(BigNumber|int|string $that): BigInteger
785
    {
786
        $that = BigInteger::of($that);
5,304✔
787

788
        if ($that->isZero()) {
5,304✔
789
            return $this->abs();
72✔
790
        }
791

792
        if ($this->isZero()) {
5,232✔
793
            return $that->abs();
132✔
794
        }
795

796
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
5,100✔
797

798
        return new BigInteger($value);
5,100✔
799
    }
800

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

816
        if ($this->isZero() || $that->isZero()) {
561✔
817
            return BigInteger::zero();
99✔
818
        }
819

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

822
        return new BigInteger($value);
462✔
823
    }
824

825
    /**
826
     * Returns the integer square root of this number, rounded according to the given rounding mode.
827
     *
828
     * @param RoundingMode $roundingMode An optional rounding mode, defaults to Unnecessary.
829
     *
830
     * @throws NegativeNumberException    If this number is negative.
831
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and the number is not a perfect square.
832
     *
833
     * @pure
834
     */
835
    public function sqrt(RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
836
    {
837
        if ($this->isNegative()) {
10,623✔
838
            throw NegativeNumberException::squareRootOfNegativeNumber();
3✔
839
        }
840

841
        $calculator = CalculatorRegistry::get();
10,620✔
842

843
        $sqrt = $calculator->sqrt($this->value);
10,620✔
844

845
        // For Down and Floor (equivalent for non-negative numbers), return floor sqrt
846
        if ($roundingMode === RoundingMode::Down || $roundingMode === RoundingMode::Floor) {
10,620✔
847
            return new BigInteger($sqrt);
2,130✔
848
        }
849

850
        // Check if the sqrt is exact
851
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
852
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
853

854
        if ($remainder === '0') {
8,490✔
855
            // sqrt is exact
856
            return new BigInteger($sqrt);
5,385✔
857
        }
858

859
        // sqrt is not exact
860
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
861
            throw RoundingNecessaryException::integerSquareRootNotExact();
390✔
862
        }
863

864
        // For Up and Ceiling (equivalent for non-negative numbers), round up
865
        if ($roundingMode === RoundingMode::Up || $roundingMode === RoundingMode::Ceiling) {
2,715✔
866
            return new BigInteger($calculator->add($sqrt, '1'));
780✔
867
        }
868

869
        // For Half* modes, compare our number to the midpoint of the interval [s², (s+1)²[.
870
        // The midpoint is s² + s + 0.5. Comparing n >= s² + s + 0.5 with remainder = n − s²
871
        // is equivalent to comparing 2*remainder >= 2*s + 1.
872
        $twoRemainder = $calculator->mul($remainder, '2');
1,935✔
873
        $threshold = $calculator->add($calculator->mul($sqrt, '2'), '1');
1,935✔
874
        $cmp = $calculator->cmp($twoRemainder, $threshold);
1,935✔
875

876
        // We're supposed to increment (round up) when:
877
        //   - HalfUp, HalfCeiling => $cmp >= 0
878
        //   - HalfDown, HalfFloor => $cmp > 0
879
        //   - HalfEven => $cmp > 0 || ($cmp === 0 && $sqrt % 2 === 1)
880
        // But 2*remainder is always even and 2*s + 1 is always odd, so $cmp is never zero.
881
        // Therefore, all Half* modes simplify to:
882
        if ($cmp > 0) {
1,935✔
883
            $sqrt = $calculator->add($sqrt, '1');
990✔
884
        }
885

886
        return new BigInteger($sqrt);
1,935✔
887
    }
888

889
    #[Override]
890
    public function negated(): static
891
    {
892
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,855✔
893
    }
894

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

910
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
911
    }
912

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

928
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
929
    }
930

931
    /**
932
     * Returns the integer bitwise-xor combined with another integer.
933
     *
934
     * This method returns a negative BigInteger if and only if exactly one of the operands is negative.
935
     *
936
     * @param BigNumber|int|string $that The operand. Must be convertible to a BigInteger.
937
     *
938
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
939
     *
940
     * @pure
941
     */
942
    public function xor(BigNumber|int|string $that): BigInteger
943
    {
944
        $that = BigInteger::of($that);
144✔
945

946
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
947
    }
948

949
    /**
950
     * Returns the bitwise-not of this BigInteger.
951
     *
952
     * @pure
953
     */
954
    public function not(): BigInteger
955
    {
956
        return $this->negated()->minus(1);
57✔
957
    }
958

959
    /**
960
     * Returns the integer left shifted by a given number of bits.
961
     *
962
     * @pure
963
     */
964
    public function shiftedLeft(int $bits): BigInteger
965
    {
966
        if ($bits === 0) {
594✔
967
            return $this;
6✔
968
        }
969

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

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

977
    /**
978
     * Returns the integer right shifted by a given number of bits.
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 < 0) {
1,452✔
989
            return $this->shiftedLeft(-$bits);
195✔
990
        }
991

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

994
        if ($this->isPositiveOrZero()) {
1,257✔
995
            return $this->quotient($operand);
672✔
996
        }
997

998
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
999
    }
1000

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

1015
        if ($this->isNegative()) {
321✔
1016
            return $this->abs()->minus(1)->getBitLength();
120✔
1017
        }
1018

1019
        return strlen($this->toBase(2));
315✔
1020
    }
1021

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

1034
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
1035
            if ($n->isOdd()) {
81✔
1036
                return $i;
78✔
1037
            }
1038

1039
            $n = $n->shiftedRight(1);
51✔
1040
        }
1041

1042
        return -1;
3✔
1043
    }
1044

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

1062
        return $this->shiftedRight($n)->isOdd();
870✔
1063
    }
1064

1065
    /**
1066
     * Returns whether this number is even.
1067
     *
1068
     * @pure
1069
     */
1070
    public function isEven(): bool
1071
    {
1072
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
1073
    }
1074

1075
    /**
1076
     * Returns whether this number is odd.
1077
     *
1078
     * @pure
1079
     */
1080
    public function isOdd(): bool
1081
    {
1082
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
1083
    }
1084

1085
    #[Override]
1086
    public function compareTo(BigNumber|int|string $that): int
1087
    {
1088
        $that = BigNumber::of($that);
3,173✔
1089

1090
        if ($that instanceof BigInteger) {
3,173✔
1091
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
3,119✔
1092
        }
1093

1094
        return -$that->compareTo($this);
120✔
1095
    }
1096

1097
    #[Override]
1098
    public function getSign(): int
1099
    {
1100
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
22,286✔
1101
    }
1102

1103
    #[Override]
1104
    public function toBigInteger(): BigInteger
1105
    {
1106
        return $this;
24,827✔
1107
    }
1108

1109
    #[Override]
1110
    public function toBigDecimal(): BigDecimal
1111
    {
1112
        return self::newBigDecimal($this->value);
4,956✔
1113
    }
1114

1115
    #[Override]
1116
    public function toBigRational(): BigRational
1117
    {
1118
        return self::newBigRational($this, BigInteger::one(), false, false);
672✔
1119
    }
1120

1121
    #[Override]
1122
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1123
    {
1124
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1125
    }
1126

1127
    #[Override]
1128
    public function toInt(): int
1129
    {
1130
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1131

1132
        if ($intValue === false) {
87✔
1133
            throw IntegerOverflowException::integerOutOfRange($this);
15✔
1134
        }
1135

1136
        return $intValue;
72✔
1137
    }
1138

1139
    #[Override]
1140
    public function toFloat(): float
1141
    {
1142
        return (float) $this->value;
183✔
1143
    }
1144

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

1160
        if ($base < 2 || $base > 36) {
1,287✔
1161
            throw InvalidArgumentException::baseOutOfRange($base);
15✔
1162
        }
1163

1164
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,272✔
1165
    }
1166

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

1187
        if ($base < 2) {
144✔
1188
            throw InvalidArgumentException::alphabetTooShort();
6✔
1189
        }
1190

1191
        if (strlen(count_chars($alphabet, 3)) !== $base) {
138✔
1192
            throw InvalidArgumentException::duplicateCharsInAlphabet();
9✔
1193
        }
1194

1195
        if ($this->isNegative()) {
129✔
1196
            throw NegativeNumberException::toArbitraryBaseOfNegativeNumber();
3✔
1197
        }
1198

1199
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1200
    }
1201

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

1228
        $hex = $this->abs()->toBase(16);
531✔
1229

1230
        if (strlen($hex) % 2 !== 0) {
531✔
1231
            $hex = '0' . $hex;
219✔
1232
        }
1233

1234
        $baseHexLength = strlen($hex);
531✔
1235

1236
        if ($signed) {
531✔
1237
            if ($this->isNegative()) {
492✔
1238
                $bin = hex2bin($hex);
453✔
1239
                assert($bin !== false);
1240

1241
                $hex = bin2hex(~$bin);
453✔
1242
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1243

1244
                $hexLength = strlen($hex);
453✔
1245

1246
                if ($hexLength < $baseHexLength) {
453✔
1247
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1248
                }
1249

1250
                if ($hex[0] < '8') {
453✔
1251
                    $hex = 'FF' . $hex;
114✔
1252
                }
1253
            } else {
1254
                if ($hex[0] >= '8') {
39✔
1255
                    $hex = '00' . $hex;
21✔
1256
                }
1257
            }
1258
        }
1259

1260
        $result = hex2bin($hex);
531✔
1261
        assert($result !== false);
1262

1263
        return $result;
531✔
1264
    }
1265

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

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

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

1304
        /** @phpstan-ignore deadCode.unreachable */
1305
        $this->value = $data['value'];
6✔
1306
    }
1307

1308
    #[Override]
1309
    protected static function from(BigNumber $number): static
1310
    {
1311
        return $number->toBigInteger();
24,929✔
1312
    }
1313

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

1328
        try {
1329
            $randomBytes = $randomBytesGenerator($byteLength);
174✔
1330
        } catch (Throwable $e) {
6✔
1331
            throw RandomSourceException::randomSourceFailure($e);
6✔
1332
        }
1333

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

1339
        if (strlen($randomBytes) !== $byteLength) {
162✔
1340
            throw RandomSourceException::invalidRandomBytesLength($byteLength, strlen($randomBytes));
3✔
1341
        }
1342

1343
        return $randomBytes;
159✔
1344
    }
1345

1346
    /**
1347
     * @pure
1348
     */
1349
    private function isOne(): bool
1350
    {
1351
        return $this->value === '1';
5,667✔
1352
    }
1353

1354
    /**
1355
     * @pure
1356
     */
1357
    private function isMinusOne(): bool
1358
    {
1359
        return $this->value === '-1';
3,993✔
1360
    }
1361
}
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