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

brick / math / 21788757427

07 Feb 2026 09:34PM UTC coverage: 98.528% (-0.8%) from 99.372%
21788757427

push

github

BenMorel
Remove deprecated BigRational::simplified()

1339 of 1359 relevant lines covered (98.53%)

2291.11 hits per line

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

98.38
/src/BigInteger.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Brick\Math;
6

7
use Brick\Math\Exception\DivisionByZeroException;
8
use Brick\Math\Exception\IntegerOverflowException;
9
use Brick\Math\Exception\InvalidArgumentException;
10
use Brick\Math\Exception\MathException;
11
use Brick\Math\Exception\NegativeNumberException;
12
use Brick\Math\Exception\NoInverseException;
13
use Brick\Math\Exception\NumberFormatException;
14
use Brick\Math\Exception\RoundingNecessaryException;
15
use Brick\Math\Internal\CalculatorRegistry;
16
use Brick\Math\Internal\Constants;
17
use LogicException;
18
use Override;
19

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

38
use const FILTER_VALIDATE_INT;
39

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

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

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

92
        if ($number === '') {
2,078✔
93
            throw NumberFormatException::emptyNumber();
3✔
94
        }
95

96
        $originalNumber = $number;
2,075✔
97

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

108
        if ($number === '') {
2,075✔
109
            throw NumberFormatException::invalidFormat($originalNumber);
6✔
110
        }
111

112
        $number = ltrim($number, '0');
2,069✔
113

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

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

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

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

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

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

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

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

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

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

168
        if ($number === '') {
408✔
169
            throw NumberFormatException::emptyNumber();
3✔
170
        }
171

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

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

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

180
        return new BigInteger($number);
378✔
181
    }
182

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

208
        $twosComplement = false;
1,221✔
209

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

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

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

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

224
        return $number;
315✔
225
    }
226

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

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

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

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

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

259
        $randomBytes = $randomBytesGenerator($byteLength);
159✔
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
     *                       or `$min` is greater than `$max`.
278
     */
279
    public static function randomRange(
280
        BigNumber|int|string $min,
281
        BigNumber|int|string $max,
282
        ?callable $randomBytesGenerator = null,
283
    ): BigInteger {
284
        $min = BigInteger::of($min);
84✔
285
        $max = BigInteger::of($max);
84✔
286

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

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

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

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

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

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

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

320
        return $zero;
222✔
321
    }
322

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

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

337
        return $one;
684✔
338
    }
339

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

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

354
        return $ten;
6✔
355
    }
356

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

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

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

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

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

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

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

408
        return $result;
273✔
409
    }
410

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

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

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

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

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

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

450
        if ($that->value === '0') {
1,128✔
451
            return $this;
84✔
452
        }
453

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

456
        return new BigInteger($value);
1,053✔
457
    }
458

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

472
        if ($that->value === '1') {
1,467✔
473
            return $this;
555✔
474
        }
475

476
        if ($this->value === '1') {
1,317✔
477
            return $that;
423✔
478
        }
479

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

482
        return new BigInteger($value);
1,194✔
483
    }
484

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

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

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

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

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

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

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

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

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

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

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

563
        if ($that->value === '1') {
3,003✔
564
            return $this;
1,662✔
565
        }
566

567
        if ($that->value === '0') {
2,070✔
568
            throw DivisionByZeroException::divisionByZero();
3✔
569
        }
570

571
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
2,067✔
572

573
        return new BigInteger($quotient);
2,067✔
574
    }
575

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

599
        if ($that->value === '1') {
273✔
600
            return BigInteger::zero();
24✔
601
        }
602

603
        if ($that->value === '0') {
249✔
604
            throw DivisionByZeroException::divisionByZero();
3✔
605
        }
606

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

609
        return new BigInteger($remainder);
246✔
610
    }
611

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

635
        if ($that->value === '0') {
147✔
636
            throw DivisionByZeroException::divisionByZero();
3✔
637
        }
638

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

641
        return [
144✔
642
            new BigInteger($quotient),
144✔
643
            new BigInteger($remainder),
144✔
644
        ];
144✔
645
    }
646

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

673
        if ($modulus->isZero()) {
105✔
674
            throw DivisionByZeroException::zeroModulus();
3✔
675
        }
676

677
        if ($modulus->isNegative()) {
102✔
678
            throw InvalidArgumentException::negativeModulus();
3✔
679
        }
680

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

683
        return new BigInteger($value);
99✔
684
    }
685

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

703
        if ($modulus->isZero()) {
75✔
704
            throw DivisionByZeroException::zeroModulus();
6✔
705
        }
706

707
        if ($modulus->isNegative()) {
69✔
708
            throw InvalidArgumentException::negativeModulus();
3✔
709
        }
710

711
        if ($modulus->value === '1') {
66✔
712
            return BigInteger::zero();
3✔
713
        }
714

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

717
        if ($value === null) {
63✔
718
            throw NoInverseException::noModularInverse();
15✔
719
        }
720

721
        return new BigInteger($value);
48✔
722
    }
723

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

743
        if ($modulus->isZero()) {
185✔
744
            throw DivisionByZeroException::zeroModulus();
3✔
745
        }
746

747
        if ($modulus->isNegative()) {
182✔
748
            throw InvalidArgumentException::negativeModulus();
3✔
749
        }
750

751
        if ($exponent->isNegative()) {
179✔
752
            throw InvalidArgumentException::negativeExponent();
3✔
753
        }
754

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

757
        return new BigInteger($result);
176✔
758
    }
759

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

775
        if ($that->value === '0' && $this->value[0] !== '-') {
5,256✔
776
            return $this;
66✔
777
        }
778

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

783
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
5,073✔
784

785
        return new BigInteger($value);
5,073✔
786
    }
787

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

803
        if ($this->isZero() || $that->isZero()) {
561✔
804
            return BigInteger::zero();
99✔
805
        }
806

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

809
        return new BigInteger($value);
462✔
810
    }
811

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

828
        $calculator = CalculatorRegistry::get();
10,620✔
829

830
        $sqrt = $calculator->sqrt($this->value);
10,620✔
831

832
        // For Down and Floor (equivalent for non-negative numbers), return floor sqrt
833
        if ($roundingMode === RoundingMode::Down || $roundingMode === RoundingMode::Floor) {
10,620✔
834
            return new BigInteger($sqrt);
2,130✔
835
        }
836

837
        // Check if the sqrt is exact
838
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
839
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
840

841
        if ($remainder === '0') {
8,490✔
842
            // sqrt is exact
843
            return new BigInteger($sqrt);
5,385✔
844
        }
845

846
        // sqrt is not exact
847
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
848
            throw RoundingNecessaryException::integerSquareRootNotExact();
390✔
849
        }
850

851
        // For Up and Ceiling (equivalent for non-negative numbers), round up
852
        if ($roundingMode === RoundingMode::Up || $roundingMode === RoundingMode::Ceiling) {
2,715✔
853
            return new BigInteger($calculator->add($sqrt, '1'));
780✔
854
        }
855

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

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

873
        return new BigInteger($sqrt);
1,935✔
874
    }
875

876
    #[Override]
877
    public function negated(): static
878
    {
879
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
3,816✔
880
    }
881

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

897
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
898
    }
899

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

915
        return new BigInteger(CalculatorRegistry::get()->or($this->value, $that->value));
138✔
916
    }
917

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

933
        return new BigInteger(CalculatorRegistry::get()->xor($this->value, $that->value));
144✔
934
    }
935

936
    /**
937
     * Returns the bitwise-not of this BigInteger.
938
     *
939
     * @pure
940
     */
941
    public function not(): BigInteger
942
    {
943
        return $this->negated()->minus(1);
57✔
944
    }
945

946
    /**
947
     * Returns the integer left shifted by a given number of bits.
948
     *
949
     * @throws InvalidArgumentException If the number of bits is out of range.
950
     *
951
     * @pure
952
     */
953
    public function shiftedLeft(int $bits): BigInteger
954
    {
955
        if ($bits === 0) {
594✔
956
            return $this;
6✔
957
        }
958

959
        if ($bits > Constants::MAX_BIT_SHIFT || $bits < -Constants::MAX_BIT_SHIFT) {
588✔
960
            throw InvalidArgumentException::bitShiftOutOfRange($bits);
×
961
        }
962

963
        if ($bits < 0) {
588✔
964
            return $this->shiftedRight(-$bits);
198✔
965
        }
966

967
        return $this->multipliedBy(BigInteger::of(2)->power($bits));
390✔
968
    }
969

970
    /**
971
     * Returns the integer right shifted by a given number of bits.
972
     *
973
     * @throws InvalidArgumentException If the number of bits is out of range.
974
     *
975
     * @pure
976
     */
977
    public function shiftedRight(int $bits): BigInteger
978
    {
979
        if ($bits === 0) {
1,518✔
980
            return $this;
66✔
981
        }
982

983
        if ($bits > Constants::MAX_BIT_SHIFT || $bits < -Constants::MAX_BIT_SHIFT) {
1,452✔
984
            throw InvalidArgumentException::bitShiftOutOfRange($bits);
×
985
        }
986

987
        if ($bits < 0) {
1,452✔
988
            return $this->shiftedLeft(-$bits);
195✔
989
        }
990

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

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

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

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

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

1018
        return strlen($this->toBase(2));
309✔
1019
    }
1020

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

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

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

1041
        return -1;
3✔
1042
    }
1043

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

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

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

1081
        return $this->shiftedRight($n)->isOdd();
870✔
1082
    }
1083

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

1089
        if ($that instanceof BigInteger) {
2,366✔
1090
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,258✔
1091
        }
1092

1093
        return -$that->compareTo($this);
108✔
1094
    }
1095

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

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

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

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

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

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

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

1135
        return $intValue;
72✔
1136
    }
1137

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

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

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

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

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

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

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

1194
        if ($this->value[0] === '-') {
129✔
1195
            throw NegativeNumberException::toArbitraryBaseOfNegativeNumber();
3✔
1196
        }
1197

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

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

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

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

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

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

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

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

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

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

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

1262
        return $result;
531✔
1263
    }
1264

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

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

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

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

1307
    #[Override]
1308
    protected static function from(BigNumber $number): static
1309
    {
1310
        return $number->toBigInteger();
24,869✔
1311
    }
1312
}
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