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

brick / math / 21484755187

29 Jan 2026 03:45PM UTC coverage: 99.425% (+0.004%) from 99.421%
21484755187

push

github

BenMorel
Improve BigDecimal::remainder() doc

1211 of 1218 relevant lines covered (99.43%)

2560.03 hits per line

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

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

3
declare(strict_types=1);
4

5
namespace Brick\Math;
6

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

20
use function assert;
21
use function bin2hex;
22
use function chr;
23
use function filter_var;
24
use function hex2bin;
25
use function in_array;
26
use function intdiv;
27
use function ltrim;
28
use function ord;
29
use function preg_match;
30
use function preg_quote;
31
use function random_bytes;
32
use function sprintf;
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 arbitrary-size integer.
42
 *
43
 * All methods accepting a number as a parameter accept either a BigInteger instance,
44
 * an integer, or a string representing an arbitrary size integer.
45
 */
46
final readonly class BigInteger extends BigNumber
47
{
48
    /**
49
     * The value, as a string of digits with optional leading minus sign.
50
     *
51
     * No leading zeros must be present.
52
     * No leading minus sign must be present if the number is zero.
53
     */
54
    private string $value;
55

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

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

93
        if ($base < 2 || $base > 36) {
2,090✔
94
            throw new InvalidArgumentException(sprintf('Base %d is not in range 2 to 36.', $base));
15✔
95
        }
96

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

107
        if ($number === '') {
2,075✔
108
            throw new NumberFormatException('The number cannot be empty.');
6✔
109
        }
110

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

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

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

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

125
        if (preg_match($pattern, strtolower($number), $matches) === 1) {
1,916✔
126
            throw new NumberFormatException(sprintf('"%s" is not a valid character in base %d.', $matches[0], $base));
111✔
127
        }
128

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

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

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

139
    /**
140
     * Parses a string containing an integer in an arbitrary base, using a custom alphabet.
141
     *
142
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers.
143
     *
144
     * @param string $number   The number to parse.
145
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
146
     *
147
     * @throws NumberFormatException    If the given number is empty or contains invalid chars for the given alphabet.
148
     * @throws InvalidArgumentException If the alphabet does not contain at least 2 chars.
149
     *
150
     * @pure
151
     */
152
    public static function fromArbitraryBase(string $number, string $alphabet): BigInteger
153
    {
154
        if ($number === '') {
411✔
155
            throw new NumberFormatException('The number cannot be empty.');
3✔
156
        }
157

158
        $base = strlen($alphabet);
408✔
159

160
        if ($base < 2) {
408✔
161
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
162
        }
163

164
        $pattern = '/[^' . preg_quote($alphabet, '/') . ']/';
402✔
165

166
        if (preg_match($pattern, $number, $matches) === 1) {
402✔
167
            throw NumberFormatException::charNotInAlphabet($matches[0]);
24✔
168
        }
169

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

172
        return new BigInteger($number);
378✔
173
    }
174

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

200
        $twosComplement = false;
1,221✔
201

202
        if ($signed) {
1,221✔
203
            $x = ord($value[0]);
984✔
204

205
            if (($twosComplement = ($x >= 0x80))) {
984✔
206
                $value = ~$value;
906✔
207
            }
208
        }
209

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

212
        if ($twosComplement) {
1,221✔
213
            return $number->plus(1)->negated();
906✔
214
        }
215

216
        return $number;
315✔
217
    }
218

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

237
        if ($numBits === 0) {
162✔
238
            return BigInteger::zero();
3✔
239
        }
240

241
        if ($randomBytesGenerator === null) {
159✔
242
            $randomBytesGenerator = random_bytes(...);
×
243
        }
244

245
        /** @var int<1, max> $byteLength */
246
        $byteLength = intdiv($numBits - 1, 8) + 1;
159✔
247

248
        $extraBits = ($byteLength * 8 - $numBits);
159✔
249
        $bitmask = chr(0xFF >> $extraBits);
159✔
250

251
        $randomBytes = $randomBytesGenerator($byteLength);
159✔
252
        $randomBytes[0] = $randomBytes[0] & $bitmask;
159✔
253

254
        return self::fromBytes($randomBytes, false);
159✔
255
    }
256

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

279
        if ($min->isGreaterThan($max)) {
84✔
280
            throw new InvalidArgumentException('$min cannot be greater than $max.');
3✔
281
        }
282

283
        if ($min->isEqualTo($max)) {
81✔
284
            return $min;
3✔
285
        }
286

287
        $diff = $max->minus($min);
78✔
288
        $bitLength = $diff->getBitLength();
78✔
289

290
        // try until the number is in range (50% to 100% chance of success)
291
        do {
292
            $randomNumber = self::randomBits($bitLength, $randomBytesGenerator);
78✔
293
        } while ($randomNumber->isGreaterThan($diff));
78✔
294

295
        return $randomNumber->plus($min);
78✔
296
    }
297

298
    /**
299
     * Returns a BigInteger representing zero.
300
     *
301
     * @pure
302
     */
303
    public static function zero(): BigInteger
304
    {
305
        /** @var BigInteger|null $zero */
306
        static $zero;
132✔
307

308
        if ($zero === null) {
132✔
309
            $zero = new BigInteger('0');
×
310
        }
311

312
        return $zero;
132✔
313
    }
314

315
    /**
316
     * Returns a BigInteger representing one.
317
     *
318
     * @pure
319
     */
320
    public static function one(): BigInteger
321
    {
322
        /** @var BigInteger|null $one */
323
        static $one;
513✔
324

325
        if ($one === null) {
513✔
326
            $one = new BigInteger('1');
×
327
        }
328

329
        return $one;
513✔
330
    }
331

332
    /**
333
     * Returns a BigInteger representing ten.
334
     *
335
     * @pure
336
     */
337
    public static function ten(): BigInteger
338
    {
339
        /** @var BigInteger|null $ten */
340
        static $ten;
6✔
341

342
        if ($ten === null) {
6✔
343
            $ten = new BigInteger('10');
3✔
344
        }
345

346
        return $ten;
6✔
347
    }
348

349
    /**
350
     * @param BigNumber|int|string $a    The first number. Must be convertible to a BigInteger.
351
     * @param BigNumber|int|string ...$n The subsequent numbers. Must be convertible to BigInteger.
352
     *
353
     * @throws MathException If one of the parameters cannot be converted to a BigInteger.
354
     *
355
     * @pure
356
     */
357
    public static function gcdAll(BigNumber|int|string $a, BigNumber|int|string ...$n): BigInteger
358
    {
359
        $result = BigInteger::of($a);
1,566✔
360

361
        foreach ($n as $next) {
1,566✔
362
            $result = $result->gcd(BigInteger::of($next));
1,551✔
363

364
            if ($result->isEqualTo(1)) {
1,551✔
365
                return $result;
345✔
366
            }
367
        }
368

369
        return $result;
1,221✔
370
    }
371

372
    /**
373
     * Returns the sum of this number and the given one.
374
     *
375
     * @param BigNumber|int|string $that The number to add. Must be convertible to a BigInteger.
376
     *
377
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
378
     *
379
     * @pure
380
     */
381
    public function plus(BigNumber|int|string $that): BigInteger
382
    {
383
        $that = BigInteger::of($that);
1,605✔
384

385
        if ($that->value === '0') {
1,605✔
386
            return $this;
30✔
387
        }
388

389
        if ($this->value === '0') {
1,575✔
390
            return $that;
69✔
391
        }
392

393
        $value = CalculatorRegistry::get()->add($this->value, $that->value);
1,527✔
394

395
        return new BigInteger($value);
1,527✔
396
    }
397

398
    /**
399
     * Returns the difference of this number and the given one.
400
     *
401
     * @param BigNumber|int|string $that The number to subtract. Must be convertible to a BigInteger.
402
     *
403
     * @throws MathException If the number is not valid, or is not convertible to a BigInteger.
404
     *
405
     * @pure
406
     */
407
    public function minus(BigNumber|int|string $that): BigInteger
408
    {
409
        $that = BigInteger::of($that);
966✔
410

411
        if ($that->value === '0') {
966✔
412
            return $this;
30✔
413
        }
414

415
        $value = CalculatorRegistry::get()->sub($this->value, $that->value);
945✔
416

417
        return new BigInteger($value);
945✔
418
    }
419

420
    /**
421
     * Returns the product of this number and the given one.
422
     *
423
     * @param BigNumber|int|string $that The multiplier. Must be convertible to a BigInteger.
424
     *
425
     * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigInteger.
426
     *
427
     * @pure
428
     */
429
    public function multipliedBy(BigNumber|int|string $that): BigInteger
430
    {
431
        $that = BigInteger::of($that);
1,242✔
432

433
        if ($that->value === '1') {
1,242✔
434
            return $this;
393✔
435
        }
436

437
        if ($this->value === '1') {
1,179✔
438
            return $that;
357✔
439
        }
440

441
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
1,089✔
442

443
        return new BigInteger($value);
1,089✔
444
    }
445

446
    /**
447
     * Returns the result of the division of this number by the given one.
448
     *
449
     * @param BigNumber|int|string $that         The divisor. Must be convertible to a BigInteger.
450
     * @param RoundingMode         $roundingMode An optional rounding mode, defaults to Unnecessary.
451
     *
452
     * @throws MathException If the divisor is not a valid number, is not convertible to a BigInteger, is zero,
453
     *                       or RoundingMode::Unnecessary is used and the remainder is not zero.
454
     *
455
     * @pure
456
     */
457
    public function dividedBy(BigNumber|int|string $that, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
458
    {
459
        $that = BigInteger::of($that);
1,977✔
460

461
        if ($that->value === '1') {
1,968✔
462
            return $this;
3✔
463
        }
464

465
        if ($that->value === '0') {
1,965✔
466
            throw DivisionByZeroException::divisionByZero();
6✔
467
        }
468

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

471
        return new BigInteger($result);
1,866✔
472
    }
473

474
    /**
475
     * Limits (clamps) this number between the given minimum and maximum values.
476
     *
477
     * If the number is lower than $min, returns a copy of $min.
478
     * If the number is greater than $max, returns a copy of $max.
479
     * Otherwise, returns this number unchanged.
480
     *
481
     * @param BigNumber|int|string $min The minimum. Must be convertible to a BigInteger.
482
     * @param BigNumber|int|string $max The maximum. Must be convertible to a BigInteger.
483
     *
484
     * @throws MathException If min/max are not convertible to a BigInteger.
485
     */
486
    public function clamp(BigNumber|int|string $min, BigNumber|int|string $max): BigInteger
487
    {
488
        $min = BigInteger::of($min);
33✔
489
        $max = BigInteger::of($max);
33✔
490

491
        if ($min->isGreaterThan($max)) {
33✔
492
            throw new InvalidArgumentException('Minimum value must be less than or equal to maximum value.');
3✔
493
        }
494

495
        if ($this->isLessThan($min)) {
30✔
496
            return $min;
9✔
497
        } elseif ($this->isGreaterThan($max)) {
21✔
498
            return $max;
3✔
499
        }
500

501
        return $this;
18✔
502
    }
503

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

517
        if ($exponent === 1) {
1,824✔
518
            return $this;
204✔
519
        }
520

521
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
1,620✔
522
            throw new InvalidArgumentException(sprintf(
6✔
523
                'The exponent %d is not in the range 0 to %d.',
6✔
524
                $exponent,
6✔
525
                Calculator::MAX_POWER,
6✔
526
            ));
6✔
527
        }
528

529
        return new BigInteger(CalculatorRegistry::get()->pow($this->value, $exponent));
1,614✔
530
    }
531

532
    /**
533
     * Returns the quotient of the division of this number by the given one.
534
     *
535
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
536
     *
537
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigInteger.
538
     * @throws DivisionByZeroException If the divisor is zero.
539
     *
540
     * @pure
541
     */
542
    public function quotient(BigNumber|int|string $that): BigInteger
543
    {
544
        $that = BigInteger::of($that);
2,712✔
545

546
        if ($that->value === '1') {
2,712✔
547
            return $this;
1,389✔
548
        }
549

550
        if ($that->value === '0') {
1,857✔
551
            throw DivisionByZeroException::divisionByZero();
3✔
552
        }
553

554
        $quotient = CalculatorRegistry::get()->divQ($this->value, $that->value);
1,854✔
555

556
        return new BigInteger($quotient);
1,854✔
557
    }
558

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

575
        if ($that->value === '1') {
228✔
576
            return BigInteger::zero();
33✔
577
        }
578

579
        if ($that->value === '0') {
195✔
580
            throw DivisionByZeroException::divisionByZero();
3✔
581
        }
582

583
        $remainder = CalculatorRegistry::get()->divR($this->value, $that->value);
192✔
584

585
        return new BigInteger($remainder);
192✔
586
    }
587

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

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

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

610
        return [
144✔
611
            new BigInteger($quotient),
144✔
612
            new BigInteger($remainder),
144✔
613
        ];
144✔
614
    }
615

616
    /**
617
     * Returns the modulo of this number and the given one.
618
     *
619
     * The modulo operation yields the same result as the remainder operation when both operands are of the same sign,
620
     * and may differ when signs are different.
621
     *
622
     * The result of the modulo operation, when non-zero, has the same sign as the divisor.
623
     *
624
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigInteger.
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 mod(BigNumber|int|string $that): BigInteger
632
    {
633
        $that = BigInteger::of($that);
195✔
634

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

639
        $value = CalculatorRegistry::get()->mod($this->value, $that->value);
192✔
640

641
        return new BigInteger($value);
192✔
642
    }
643

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

660
        if ($modulus->value === '0') {
75✔
661
            throw DivisionByZeroException::modulusMustNotBeZero();
6✔
662
        }
663

664
        if ($modulus->isNegative()) {
69✔
665
            throw new NegativeNumberException('Modulus must not be negative.');
3✔
666
        }
667

668
        if ($modulus->value === '1') {
66✔
669
            return BigInteger::zero();
3✔
670
        }
671

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

674
        if ($value === null) {
63✔
675
            throw NoInverseException::noModularInverse();
15✔
676
        }
677

678
        return new BigInteger($value);
48✔
679
    }
680

681
    /**
682
     * Returns this number raised into power with modulo.
683
     *
684
     * This operation only works on positive numbers.
685
     *
686
     * @param BigNumber|int|string $exponent The exponent. Must be positive or zero.
687
     * @param BigNumber|int|string $modulus  The modulus. Must be strictly positive.
688
     *
689
     * @throws MathException           If the exponent or modulus is not valid, or not convertible to a BigInteger.
690
     * @throws NegativeNumberException If any of the operands is negative.
691
     * @throws DivisionByZeroException If the modulus is zero.
692
     *
693
     * @pure
694
     */
695
    public function modPow(BigNumber|int|string $exponent, BigNumber|int|string $modulus): BigInteger
696
    {
697
        $exponent = BigInteger::of($exponent);
47✔
698
        $modulus = BigInteger::of($modulus);
47✔
699

700
        if ($this->isNegative() || $exponent->isNegative() || $modulus->isNegative()) {
47✔
701
            throw new NegativeNumberException('The operands cannot be negative.');
9✔
702
        }
703

704
        if ($modulus->isZero()) {
38✔
705
            throw DivisionByZeroException::modulusMustNotBeZero();
3✔
706
        }
707

708
        $result = CalculatorRegistry::get()->modPow($this->value, $exponent->value, $modulus->value);
35✔
709

710
        return new BigInteger($result);
35✔
711
    }
712

713
    /**
714
     * Returns the greatest common divisor of this number and the given one.
715
     *
716
     * The GCD is always positive, unless both operands are zero, in which case it is zero.
717
     *
718
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
719
     *
720
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
721
     *
722
     * @pure
723
     */
724
    public function gcd(BigNumber|int|string $that): BigInteger
725
    {
726
        $that = BigInteger::of($that);
4,944✔
727

728
        if ($that->value === '0' && $this->value[0] !== '-') {
4,944✔
729
            return $this;
60✔
730
        }
731

732
        if ($this->value === '0' && $that->value[0] !== '-') {
4,884✔
733
            return $that;
273✔
734
        }
735

736
        $value = CalculatorRegistry::get()->gcd($this->value, $that->value);
4,797✔
737

738
        return new BigInteger($value);
4,797✔
739
    }
740

741
    /**
742
     * Returns the integer square root of this number, rounded according to the given rounding mode.
743
     *
744
     * @param RoundingMode $roundingMode The rounding mode to use, defaults to Unnecessary.
745
     *
746
     * @throws NegativeNumberException    If this number is negative.
747
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, and the number is not a perfect square.
748
     *
749
     * @pure
750
     */
751
    public function sqrt(RoundingMode $roundingMode = RoundingMode::Unnecessary): BigInteger
752
    {
753
        if ($this->value[0] === '-') {
10,623✔
754
            throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
3✔
755
        }
756

757
        $calculator = CalculatorRegistry::get();
10,620✔
758

759
        $sqrt = $calculator->sqrt($this->value);
10,620✔
760

761
        // For Down and Floor (equivalent for non-negative numbers), return floor sqrt
762
        if ($roundingMode === RoundingMode::Down || $roundingMode === RoundingMode::Floor) {
10,620✔
763
            return new BigInteger($sqrt);
2,130✔
764
        }
765

766
        // Check if the sqrt is exact
767
        $s2 = $calculator->mul($sqrt, $sqrt);
8,490✔
768
        $remainder = $calculator->sub($this->value, $s2);
8,490✔
769

770
        if ($remainder === '0') {
8,490✔
771
            // sqrt is exact
772
            return new BigInteger($sqrt);
5,385✔
773
        }
774

775
        // sqrt is not exact
776
        if ($roundingMode === RoundingMode::Unnecessary) {
3,105✔
777
            throw RoundingNecessaryException::roundingNecessary();
390✔
778
        }
779

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

785
        // For Half* modes, compare our number to the midpoint of the interval [s², (s+1)²[.
786
        // The midpoint is s² + s + 0.5. Comparing n >= s² + s + 0.5 with remainder = n − s²
787
        // is equivalent to comparing 2*remainder >= 2*s + 1.
788
        $twoRemainder = $calculator->mul($remainder, '2');
1,935✔
789
        $threshold = $calculator->add($calculator->mul($sqrt, '2'), '1');
1,935✔
790
        $cmp = $calculator->cmp($twoRemainder, $threshold);
1,935✔
791

792
        // We're supposed to increment (round up) when:
793
        //   - HalfUp, HalfCeiling => $cmp >= 0
794
        //   - HalfDown, HalfFloor => $cmp > 0
795
        //   - HalfEven => $cmp > 0 || ($cmp === 0 && $sqrt % 2 === 1)
796
        // But 2*remainder is always even and 2*s + 1 is always odd, so $cmp is never zero.
797
        // Therefore, all Half* modes simplify to:
798
        if ($cmp > 0) {
1,935✔
799
            $sqrt = $calculator->add($sqrt, '1');
990✔
800
        }
801

802
        return new BigInteger($sqrt);
1,935✔
803
    }
804

805
    /**
806
     * Returns the absolute value of this number.
807
     *
808
     * @pure
809
     */
810
    public function abs(): BigInteger
811
    {
812
        return $this->isNegative() ? $this->negated() : $this;
678✔
813
    }
814

815
    /**
816
     * Returns the inverse of this number.
817
     *
818
     * @pure
819
     */
820
    public function negated(): BigInteger
821
    {
822
        return new BigInteger(CalculatorRegistry::get()->neg($this->value));
2,850✔
823
    }
824

825
    /**
826
     * Returns the integer bitwise-and combined with another integer.
827
     *
828
     * This method returns a negative BigInteger if and only if both operands are negative.
829
     *
830
     * @param BigNumber|int|string $that The operand. Must be convertible to an integer number.
831
     *
832
     * @throws MathException If the operand is not valid, or is not convertible to a BigInteger.
833
     *
834
     * @pure
835
     */
836
    public function and(BigNumber|int|string $that): BigInteger
837
    {
838
        $that = BigInteger::of($that);
153✔
839

840
        return new BigInteger(CalculatorRegistry::get()->and($this->value, $that->value));
153✔
841
    }
842

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

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

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

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

879
    /**
880
     * Returns the bitwise-not of this BigInteger.
881
     *
882
     * @pure
883
     */
884
    public function not(): BigInteger
885
    {
886
        return $this->negated()->minus(1);
57✔
887
    }
888

889
    /**
890
     * Returns the integer left shifted by a given number of bits.
891
     *
892
     * @throws InvalidArgumentException If the number of bits is out of range.
893
     *
894
     * @pure
895
     */
896
    public function shiftedLeft(int $bits): BigInteger
897
    {
898
        if ($bits === 0) {
594✔
899
            return $this;
6✔
900
        }
901

902
        if ($bits < 0) {
588✔
903
            return $this->shiftedRight(-$bits);
198✔
904
        }
905

906
        return $this->multipliedBy(BigInteger::of(2)->power($bits));
390✔
907
    }
908

909
    /**
910
     * Returns the integer right shifted by a given number of bits.
911
     *
912
     * @throws InvalidArgumentException If the number of bits is out of range.
913
     *
914
     * @pure
915
     */
916
    public function shiftedRight(int $bits): BigInteger
917
    {
918
        if ($bits === 0) {
1,518✔
919
            return $this;
66✔
920
        }
921

922
        if ($bits < 0) {
1,452✔
923
            return $this->shiftedLeft(-$bits);
195✔
924
        }
925

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

928
        if ($this->isPositiveOrZero()) {
1,257✔
929
            return $this->quotient($operand);
672✔
930
        }
931

932
        return $this->dividedBy($operand, RoundingMode::Up);
585✔
933
    }
934

935
    /**
936
     * Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
937
     *
938
     * For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation.
939
     * Computes (ceil(log2(this < 0 ? -this : this+1))).
940
     *
941
     * @pure
942
     */
943
    public function getBitLength(): int
944
    {
945
        if ($this->value === '0') {
321✔
946
            return 0;
12✔
947
        }
948

949
        if ($this->isNegative()) {
315✔
950
            return $this->abs()->minus(1)->getBitLength();
120✔
951
        }
952

953
        return strlen($this->toBase(2));
309✔
954
    }
955

956
    /**
957
     * Returns the index of the rightmost (lowest-order) one bit in this BigInteger.
958
     *
959
     * Returns -1 if this BigInteger contains no one bits.
960
     *
961
     * @pure
962
     */
963
    public function getLowestSetBit(): int
964
    {
965
        $n = $this;
81✔
966
        $bitLength = $this->getBitLength();
81✔
967

968
        for ($i = 0; $i <= $bitLength; $i++) {
81✔
969
            if ($n->isOdd()) {
81✔
970
                return $i;
78✔
971
            }
972

973
            $n = $n->shiftedRight(1);
51✔
974
        }
975

976
        return -1;
3✔
977
    }
978

979
    /**
980
     * Returns whether this number is even.
981
     *
982
     * @pure
983
     */
984
    public function isEven(): bool
985
    {
986
        return in_array($this->value[-1], ['0', '2', '4', '6', '8'], true);
60✔
987
    }
988

989
    /**
990
     * Returns whether this number is odd.
991
     *
992
     * @pure
993
     */
994
    public function isOdd(): bool
995
    {
996
        return in_array($this->value[-1], ['1', '3', '5', '7', '9'], true);
1,011✔
997
    }
998

999
    /**
1000
     * Returns true if and only if the designated bit is set.
1001
     *
1002
     * Computes ((this & (1<<n)) != 0).
1003
     *
1004
     * @param int $n The bit to test, 0-based.
1005
     *
1006
     * @throws InvalidArgumentException If the bit to test is negative.
1007
     *
1008
     * @pure
1009
     */
1010
    public function testBit(int $n): bool
1011
    {
1012
        if ($n < 0) {
873✔
1013
            throw new InvalidArgumentException('The bit to test cannot be negative.');
3✔
1014
        }
1015

1016
        return $this->shiftedRight($n)->isOdd();
870✔
1017
    }
1018

1019
    #[Override]
1020
    public function compareTo(BigNumber|int|string $that): int
1021
    {
1022
        $that = BigNumber::of($that);
2,318✔
1023

1024
        if ($that instanceof BigInteger) {
2,318✔
1025
            return CalculatorRegistry::get()->cmp($this->value, $that->value);
2,210✔
1026
        }
1027

1028
        return -$that->compareTo($this);
108✔
1029
    }
1030

1031
    #[Override]
1032
    public function getSign(): int
1033
    {
1034
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
3,275✔
1035
    }
1036

1037
    #[Override]
1038
    public function toBigInteger(): BigInteger
1039
    {
1040
        return $this;
23,858✔
1041
    }
1042

1043
    #[Override]
1044
    public function toBigDecimal(): BigDecimal
1045
    {
1046
        return self::newBigDecimal($this->value);
5,157✔
1047
    }
1048

1049
    #[Override]
1050
    public function toBigRational(): BigRational
1051
    {
1052
        return self::newBigRational($this, BigInteger::one(), false, false);
471✔
1053
    }
1054

1055
    #[Override]
1056
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
1057
    {
1058
        return $this->toBigDecimal()->toScale($scale, $roundingMode);
9✔
1059
    }
1060

1061
    #[Override]
1062
    public function toInt(): int
1063
    {
1064
        $intValue = filter_var($this->value, FILTER_VALIDATE_INT);
87✔
1065

1066
        if ($intValue === false) {
87✔
1067
            throw IntegerOverflowException::toIntOverflow($this);
15✔
1068
        }
1069

1070
        return $intValue;
72✔
1071
    }
1072

1073
    #[Override]
1074
    public function toFloat(): float
1075
    {
1076
        return (float) $this->value;
42✔
1077
    }
1078

1079
    /**
1080
     * Returns a string representation of this number in the given base.
1081
     *
1082
     * The output will always be lowercase for bases greater than 10.
1083
     *
1084
     * @throws InvalidArgumentException If the base is out of range.
1085
     *
1086
     * @pure
1087
     */
1088
    public function toBase(int $base): string
1089
    {
1090
        if ($base === 10) {
1,293✔
1091
            return $this->value;
12✔
1092
        }
1093

1094
        if ($base < 2 || $base > 36) {
1,281✔
1095
            throw new InvalidArgumentException(sprintf('Base %d is out of range [2, 36]', $base));
15✔
1096
        }
1097

1098
        return CalculatorRegistry::get()->toBase($this->value, $base);
1,266✔
1099
    }
1100

1101
    /**
1102
     * Returns a string representation of this number in an arbitrary base with a custom alphabet.
1103
     *
1104
     * Because this method accepts an alphabet with any character, including dash, it does not handle negative numbers;
1105
     * a NegativeNumberException will be thrown when attempting to call this method on a negative number.
1106
     *
1107
     * @param string $alphabet The alphabet, for example '01' for base 2, or '01234567' for base 8.
1108
     *
1109
     * @throws NegativeNumberException  If this number is negative.
1110
     * @throws InvalidArgumentException If the given alphabet does not contain at least 2 chars.
1111
     *
1112
     * @pure
1113
     */
1114
    public function toArbitraryBase(string $alphabet): string
1115
    {
1116
        $base = strlen($alphabet);
135✔
1117

1118
        if ($base < 2) {
135✔
1119
            throw new InvalidArgumentException('The alphabet must contain at least 2 chars.');
6✔
1120
        }
1121

1122
        if ($this->value[0] === '-') {
129✔
1123
            throw new NegativeNumberException(__FUNCTION__ . '() does not support negative numbers.');
3✔
1124
        }
1125

1126
        return CalculatorRegistry::get()->toArbitraryBase($this->value, $alphabet, $base);
126✔
1127
    }
1128

1129
    /**
1130
     * Returns a string of bytes containing the binary representation of this BigInteger.
1131
     *
1132
     * The string is in big-endian byte-order: the most significant byte is in the zeroth element.
1133
     *
1134
     * If `$signed` is true, the output will be in two's-complement representation, and a sign bit will be prepended to
1135
     * the output. If `$signed` is false, no sign bit will be prepended, and this method will throw an exception if the
1136
     * number is negative.
1137
     *
1138
     * The string will contain the minimum number of bytes required to represent this BigInteger, including a sign bit
1139
     * if `$signed` is true.
1140
     *
1141
     * This representation is compatible with the `fromBytes()` factory method, as long as the `$signed` flags match.
1142
     *
1143
     * @param bool $signed Whether to output a signed number in two's-complement representation with a leading sign bit.
1144
     *
1145
     * @throws NegativeNumberException If $signed is false, and the number is negative.
1146
     *
1147
     * @pure
1148
     */
1149
    public function toBytes(bool $signed = true): string
1150
    {
1151
        if (! $signed && $this->isNegative()) {
534✔
1152
            throw new NegativeNumberException('Cannot convert a negative number to a byte string when $signed is false.');
3✔
1153
        }
1154

1155
        $hex = $this->abs()->toBase(16);
531✔
1156

1157
        if (strlen($hex) % 2 !== 0) {
531✔
1158
            $hex = '0' . $hex;
219✔
1159
        }
1160

1161
        $baseHexLength = strlen($hex);
531✔
1162

1163
        if ($signed) {
531✔
1164
            if ($this->isNegative()) {
492✔
1165
                $bin = hex2bin($hex);
453✔
1166
                assert($bin !== false);
1167

1168
                $hex = bin2hex(~$bin);
453✔
1169
                $hex = self::fromBase($hex, 16)->plus(1)->toBase(16);
453✔
1170

1171
                $hexLength = strlen($hex);
453✔
1172

1173
                if ($hexLength < $baseHexLength) {
453✔
1174
                    $hex = str_repeat('0', $baseHexLength - $hexLength) . $hex;
72✔
1175
                }
1176

1177
                if ($hex[0] < '8') {
453✔
1178
                    $hex = 'FF' . $hex;
114✔
1179
                }
1180
            } else {
1181
                if ($hex[0] >= '8') {
39✔
1182
                    $hex = '00' . $hex;
21✔
1183
                }
1184
            }
1185
        }
1186

1187
        $result = hex2bin($hex);
531✔
1188
        assert($result !== false);
1189

1190
        return $result;
531✔
1191
    }
1192

1193
    /**
1194
     * @return numeric-string
1195
     */
1196
    #[Override]
1197
    public function toString(): string
1198
    {
1199
        /** @var numeric-string */
1200
        return $this->value;
23,016✔
1201
    }
1202

1203
    /**
1204
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
1205
     *
1206
     * @internal
1207
     *
1208
     * @return array{value: string}
1209
     */
1210
    public function __serialize(): array
1211
    {
1212
        return ['value' => $this->value];
6✔
1213
    }
1214

1215
    /**
1216
     * This method is only here to allow unserializing the object and cannot be accessed directly.
1217
     *
1218
     * @internal
1219
     *
1220
     * @param array{value: string} $data
1221
     *
1222
     * @throws LogicException
1223
     */
1224
    public function __unserialize(array $data): void
1225
    {
1226
        /** @phpstan-ignore isset.initializedProperty */
1227
        if (isset($this->value)) {
9✔
1228
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
1229
        }
1230

1231
        /** @phpstan-ignore deadCode.unreachable */
1232
        $this->value = $data['value'];
6✔
1233
    }
1234

1235
    #[Override]
1236
    protected static function from(BigNumber $number): static
1237
    {
1238
        return $number->toBigInteger();
23,996✔
1239
    }
1240
}
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